Filter not working - java

I basically have a filter and in it's doFilter method, i'm just printing a message to console and i have applied that filter to every page of my sample web app.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>
com.mypkg.filters.LoginFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>utility.jsp</welcome-file>
and my filter code
LoginFilter.java
package com.mypkg.filters;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
//other imports
public class LoginFilter implements Filter {
#Override
public void init(FilterConfig config) throws ServletException {
System.out.println("Filter init ran!");
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
System.out.println("Filter running!");
}
#Override
public void destroy(FilterConfig config) throws ServletException {
//System.out.println("Filter destoryed!");
}
Now when i first ran this filter, i got "Filter running" message but after that i included hibernate and other libraries, it stopped working, i removed them and same result. Filter doesn't run. Checked url pattern and everything.. Clueless!!
Any pointers?

First of all, in you doFilter method you should call the next filter in the chain:
chain.doFilter(request, response);
Without this your request will not be processed further after your filter.
This can be a reason of your problem.
EDIT:
Also your destroy() method is wrong. Here how you should rewrite it:
#Override
public void destroy() {
System.out.println("Filter destoryed!");
}

Maybe you have another Filter executed before yours, that does not call chain.doFilter(), thus preventing next filters (including yours) to be executed.

Related

How to create correctly a Filter in Java EE 8 from Java code?

I want to create programmatically a Filter in Java EE 8 from Java Code, so I did this code in my application.
Gif captures: gif capture one - gif capture two
My filter is LoginFilter.java
package afrominga.filters;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
#WebFilter
public class LoginFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Hello from LoginFilter.");
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("I am running the LoginFilter tasks.");
}
#Override
public void destroy() {
System.out.println("Goodbie from LoginFilter");
}
}
I have in my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>afrominga.filters.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
</web-app>
So, at the time of to open my browser with the root path context of my application, the filter print in the output the text of my System.out, but my page is left blank and does not show me the home page. I don't understand why this happens, this would must forward to my home page because only print a text in my console.
can would someone help me? please
One problem is that your doFilter() method. Right now, your filter is just printing and not passing the request along to the next filter/your application. You just need to add one line.
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("I am running the LoginFilter tasks.");
filterChain.doFilter(request, response)
}

Preventing clickjacking attack

Currently, I'm working on a vaadin project where I'm working on preventing clickjacking attack on the project. After searching for the solution I've found that adding following snippet in web.xml would work:
<filter>
<filter-name>httpHeaderSecurity</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>antiClickJackingEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>antiClickJackingOption</param-name>
<param-value>SAMEORIGIN</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>httpHeaderSecurity</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
I've added following dependency in pom.xml:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>9.0.2</version>
</dependency>
I'm running the project on payara server.
The project runs but throw the following error:
Caused by: java.lang.ClassNotFoundException:
org.apache.catalina.filters.HttpHeaderSecurityFilter not found by
org.glassfish.main.web.core [69] at
org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1532)
at
org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:75)
at
org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1955)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at
org.apache.catalina.core.ApplicationFilterConfig.loadFilterClass(ApplicationFilterConfig.java:283)
at
org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:253)
at
org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:123)
... 50 more
Which means my solution for preventing clickjacking attack won't work :)
Any help will be appreciated :).
I've solved this in the following way using web.xml:
First created the following filter:
public class ClickjackingPreventionFilter implements Filter
{
private String mode = "DENY";
// Add X-FRAME-OPTIONS response header to tell any other browsers who not to display this //content in a frame.
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse)response;
res.addHeader("X-FRAME-OPTIONS", mode );
chain.doFilter(request, response);
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig filterConfig) {
String configMode = filterConfig.getInitParameter("mode");
if ( configMode != null ) {
mode = configMode;
}
}
}
Then configured that into web.xml like the following:
<filter>
<filter-name>ClickjackPreventionFilterDeny</filter-name>
<filter-class>com.groupbuilder.preventclickjacking.ClickjackingPreventionFilter</filter-class>
<init-param>
<param-name>mode</param-name><param-value>DENY</param-value></init-param>
</filter>
<filter-mapping>
<filter-name>ClickjackPreventionFilterDeny</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

filter that forwards to index page

I want to make a filter that would forward to /WEB-INF/index.html request to application that looks like this
http://localhost:8080/basic-application-web
Here is my filter
public class RootFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if (req.getRequestURI().equals("/basic%2Dapplication%2Dweb/")) {
req.getRequestDispatcher("/WEB-INF/index.html").forward(req, resp);
}
chain.doFilter(request, response);
}
#Override
public void destroy() {}
}
My web.xml looks like this
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://java.sun.com/xml/ns/javaee'
xmlns:web='http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd'
xsi:schemaLocation='http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaeeweb-app_2_5.xsd'
id='basic_web' version='2.5'>
<display-name>Basic web application</display-name>
<servlet>
<servlet-name>serviceServlet</servlet-name>
<servlet-class>com.pack.ServiceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>serviceServlet</servlet-name>
<url-pattern>/messaging</url-pattern>
</servlet-mapping>
<filter>
<filter-name>rootFilter</filter-name>
<filter-class>com.pack.RootFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>rootFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
However from time to time I get some weird behaviour where tomcat (I use it to deploy the war) is unable to find basic-application-web when I try to access directly using URL.
Though through tomcat manager it works fine. What is the problem? Maybe due to missing root servlet?
I moved index.html outside WEB-INF so basically the layout started to look like this
webapp
WEB-INF\web.xml
index.html
And adjusted filter to forward to /index.html instead of WEB-INF/index.html
req.getRequestDispatcher("/WEB-INF/index.html").forward(req, resp);
It has helped.

Filter servlet not working with glassfish in netbeans

This is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
<display-name>MyFilter</display-name>
<filter-name>MyFilter</filter-name>
<filter-class>AB_DB.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/MyFilter</url-pattern>
</filter-mapping>
<servlet>
<description></description>
<display-name>Profile</display-name>
<servlet-name>Profile</servlet-name>
<servlet-class>AB_DB.Profile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Profile</servlet-name>
<url-pattern>/Profile</url-pattern>
</servlet-mapping>
</web-app>
This is the filter servlet I've tried
package AB_DB;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class MyFilter implements Filter {
public MyFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String requri = ((HttpServletRequest) request).getRequestURI().substring(((HttpServletRequest) request).getContextPath().length() + 1);
System.out.println(requri);
//if request uri starts with user/ then system will forward the request to Profile servlet
if (requri.startsWith("user/")) {
//get userid from request uri
String id = requri.substring(5);
System.out.println(id);
//set attribute "user" with userid value
request.setAttribute("user", id);
//forward the request to Profile servlet
request.getRequestDispatcher("/Profile")
.forward(request, response);
} else {
chain.doFilter(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
However in the GlassFish 4 server log, there is no errors at all when running the project. The URI isnt even being printed out with 'System.out.println(id);' so I assume that the filter isnt even being injected.
Can anyone see any issues with my code? The sevlet Profile isn't being ran
You have mapped oyur filter to /MyFilter
<url-pattern>/MyFilter</url-pattern>
and that doesn't match with URL you are requesting
/user/Surname1993
so your filter won't get invoked

Tomcat server will not start up with a filter

Here is the web.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Projeto_joas</display-name>
<resource-ref>
<res-ref-name>jdbc/DiaDiaDev</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<servlet>
<display-name>FacesServlet</display-name>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<!-- <filter> -->
<!--<filter-name>FilterHibernate</filter-name> -->
<!--<filter-class>util.filter.ConexaoHibernateFilter</filter-class> -->
<!--</filter> -->
<!--<filter-mapping> -->
<!-- <filter-name>FilterHibernate</filter-name> -->
<!--<url-pattern>*.jsf</url-pattern> -->
<!--</filter-mapping> -->
</web-app>
The server runs just fine this way, if i remove the comments on the filter, it won't
start and will throw me those exceptions:
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
and
WARNING: Failed to retrieve JNDI naming context for container [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Projeto_joas]] so no cleanup was performed for that container
javax.naming.NamingException: No naming context bound to this class loader
the Filter class:
package util.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.hibernate.SessionFactory;
import util.HibernateUtil;
public class ConexaoHibernateFilter implements Filter {
private SessionFactory sf;
#Override
public void init(FilterConfig arg0) throws ServletException {
this.sf = HibernateUtil.getSessionFactory();
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain chain) throws IOException, ServletException {
try {
this.sf.getCurrentSession().beginTransaction();
chain.doFilter(servletRequest, servletResponse);
this.sf.getCurrentSession().getTransaction().commit();
this.sf.getCurrentSession().close();
} catch (Throwable ex) {
try {
if (this.sf.getCurrentSession().getTransaction().isActive()) {
this.sf.getCurrentSession().getTransaction().rollback();
}
} catch (Throwable t) {
t.printStackTrace();
}
throw new ServletException(ex);
}
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
}
For me also same error was coming. The mistake I did was I didn't add any body to destroy and init methods.
So for me it worked by simply added some print statement inside the body of the destroy and init method.
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Error 404 bad request");
// chain.doFilter(request, response);
}
#Override
public void destroy() {
System.out.println("destroyed"); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("initilized"); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}

Categories

Resources