Java Servlet Filter Example Tutorial

Filed Under: Java EE
Java Servlet Filter

Java Servlet Filter is used to intercept the client request and do some pre-processing. It can also intercept the response and do post-processing before sending to the client in web application. This is the fourth article in the series of Web Applications Tutorial, you might want to check out earlier articles too.

  1. Java Web Application
  2. Java Servlet Tutorial
  3. Servlet Session Management

Servlet Filter

In this article, we will lean about the Servlet Filter in Java. We will look into various usage of servlet filter, how can we create a filter and learn its usage with a simple web application.

  1. Why do we have Servlet Filter?
  2. Servlet Filter interface
  3. Servlet WebFilter annotation
  4. Servlet Filter configuration in web.xml
  5. Servlet Filter Example for Logging and session validation

  1. Why do we have Servlet Filter?

    In the last article, we learned how we can manage session in web application and if we want to make sure that a resource is accessible only when the user session is valid, we can achieve this using servlet session attributes. The approach is simple but if we have a lot of servlets and jsps, then it will become hard to maintain because of redundant code. If we want to change the attribute name in the future, we will have to change all the places where we have session authentication.

    That’s why we have a servlet filter. Servlet Filters are pluggable java components that we can use to intercept and process requests before they are sent to servlets and response after servlet code is finished and before container sends the response back to the client.

    Some common tasks that we can do with servlet filters are:

    • Logging request parameters to log files.
    • Authentication and autherization of request for resources.
    • Formatting of request body or header before sending it to servlet.
    • Compressing the response data sent to the client.
    • Alter response by adding some cookies, header information etc.

    As I mentioned earlier, servlet filters are pluggable and configured in deployment descriptor (web.xml) file. Servlets and filters both are unaware of each other and we can add or remove a servlet filter just by editing web.xml.

    We can have multiple filters for a single resource and we can create a chain of filters for a single resource in web.xml. We can create a Servlet Filter by implementing javax.servlet.Filter interface.

  2. Servlet Filter interface

    Servlet Filter interface is similar to Servlet interface and we need to implement it to create our own servlet filter. Servlet Filter interface contains lifecycle methods of a Filter and it’s managed by servlet container.

    Servlet Filter interface lifecycle methods are:

    1. void init(FilterConfig paramFilterConfig) – When container initializes the Filter, this is the method that gets invoked. This method is called only once in the lifecycle of filter and we should initialize any resources in this method. FilterConfig is used by container to provide init parameters and servlet context object to the Filter. We can throw ServletException in this method.
    2. doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain paramFilterChain) – This is the method invoked every time by container when it has to apply filter to a resource. Container provides request and response object references to filter as argument. FilterChain is used to invoke the next filter in the chain. This is a great example of Chain of Responsibility Pattern.
    3. void destroy() – When container offloads the Filter instance, it invokes the destroy() method. This is the method where we can close any resources opened by filter. This method is called only once in the lifetime of filter.
  3. Servlet WebFilter annotation

    javax.servlet.annotation.WebFilter was introduced in Servlet 3.0 and we can use this annotation to declare a servlet filter. We can use this annotation to define init parameters, filter name and description, servlets, url patterns and dispatcher types to apply the filter. If you make frequent changes to the filter configurations, its better to use web.xml because that will not require you to recompile the filter class.

    Read: Java Annotations Tutorial

  4. Servlet Filter configuration in web.xml

    We can declare a servlet filter in web.xml like below.

    
    <filter>
      <filter-name>RequestLoggingFilter</filter-name> <!-- mandatory -->
      <filter-class>com.journaldev.servlet.filters.RequestLoggingFilter</filter-class> <!-- mandatory -->
      <init-param> <!-- optional -->
      <param-name>test</param-name>
      <param-value>testValue</param-value>
      </init-param>
    </filter>
    

    We can map a Filter to servlet classes or url-patterns like below.

    
    <filter-mapping>
      <filter-name>RequestLoggingFilter</filter-name> <!-- mandatory -->
      <url-pattern>/*</url-pattern> <!-- either url-pattern or servlet-name is mandatory -->
      <servlet-name>LoginServlet</servlet-name>
      <dispatcher>REQUEST</dispatcher>
    </filter-mapping>
    

    Note: While creating the filter chain for a servlet, container first processes the url-patterns and then servlet-names, so if you have to make sure that filters are getting executed in a particular order, give extra attention while defining the filter mapping.

    Servlet Filters are generally used for client requests but sometimes we want to apply filters with RequestDispatcher also, we can use dispatcher element in this case, the possible values are REQUEST, FORWARD, INCLUDE, ERROR and ASYNC. If no dispatcher is defined then it’s applied only to client requests.

  5. Servlet Filter Example for Logging and session validation

    In our servlet filter example, we will create filters to log request cookies and parameters and validate session to all the resources except static HTMLs and LoginServlet because it will not have a session.

    We will create a dynamic web project ServletFilterExample whose project structure will look like the below image.

    Servlet Filter Example, Java Filter

    login.html is the entry point of our application where the user will provide the login id and password for authentication.

    login.html code:

    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="US-ASCII">
    <title>Login Page</title>
    </head>
    <body>
    
    <form action="LoginServlet" method="post">
    
    Username: <input type="text" name="user">
    <br>
    Password: <input type="password" name="pwd">
    <br>
    <input type="submit" value="Login">
    </form>
    </body>
    </html>
    

    LoginServlet is used to authenticate the request from the client for login.

    
    package com.journaldev.servlet.session;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * Servlet implementation class LoginServlet
     */
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	private final String userID = "admin";
    	private final String password = "password";
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		// get request parameters for userID and password
    		String user = request.getParameter("user");
    		String pwd = request.getParameter("pwd");
    		
    		if(userID.equals(user) && password.equals(pwd)){
    			HttpSession session = request.getSession();
    			session.setAttribute("user", "Pankaj");
    			//setting session to expiry in 30 mins
    			session.setMaxInactiveInterval(30*60);
    			Cookie userName = new Cookie("user", user);
    			userName.setMaxAge(30*60);
    			response.addCookie(userName);
    			response.sendRedirect("LoginSuccess.jsp");
    		}else{
    			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
    			PrintWriter out= response.getWriter();
    			out.println("<font color=red>Either user name or password is wrong.</font>");
    			rd.include(request, response);
    		}
    
    	}
    
    }
    

    When the client is authenticated, it’s forwarded to LoginSuccess.jsp

    LoginSuccess.jsp code:

    
    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    //allow access only if session exists
    String user = (String) session.getAttribute("user");
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    	if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
    }
    }
    %>
    <h3>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3>
    <br>
    User=<%=user %>
    <br>
    <a href="CheckoutPage.jsp">Checkout Page</a>
    <form action="LogoutServlet" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    

    Notice that there is no session validation logic in the above JSP. It contains a link to another JSP page, CheckoutPage.jsp.

    CheckoutPage.jsp code:

    
    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    }
    }
    %>
    <h3>Hi <%=userName %>, do the checkout.</h3>
    <br>
    <form action="LogoutServlet" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    

    LogoutServlet is invoked when a client clicks on the Logout button in any of the JSP pages.

    
    package com.journaldev.servlet.session;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * Servlet implementation class LogoutServlet
     */
    @WebServlet("/LogoutServlet")
    public class LogoutServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        	response.setContentType("text/html");
        	Cookie[] cookies = request.getCookies();
        	if(cookies != null){
        	for(Cookie cookie : cookies){
        		if(cookie.getName().equals("JSESSIONID")){
        			System.out.println("JSESSIONID="+cookie.getValue());
        			break;
        		}
        	}
        	}
        	//invalidate the session if exists
        	HttpSession session = request.getSession(false);
        	System.out.println("User="+session.getAttribute("user"));
        	if(session != null){
        		session.invalidate();
        	}
        	response.sendRedirect("login.html");
        }
    
    }
    

    Now we will create logging and authentication servlet filter classes.

    
    package com.journaldev.servlet.filters;
    
    import java.io.IOException;
    import java.util.Enumeration;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * Servlet Filter implementation class RequestLoggingFilter
     */
    @WebFilter("/RequestLoggingFilter")
    public class RequestLoggingFilter implements Filter {
    
    	private ServletContext context;
    	
    	public void init(FilterConfig fConfig) throws ServletException {
    		this.context = fConfig.getServletContext();
    		this.context.log("RequestLoggingFilter initialized");
    	}
    
    	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    		HttpServletRequest req = (HttpServletRequest) request;
    		Enumeration<String> params = req.getParameterNames();
    		while(params.hasMoreElements()){
    			String name = params.nextElement();
    			String value = request.getParameter(name);
    			this.context.log(req.getRemoteAddr() + "::Request Params::{"+name+"="+value+"}");
    		}
    		
    		Cookie[] cookies = req.getCookies();
    		if(cookies != null){
    			for(Cookie cookie : cookies){
    				this.context.log(req.getRemoteAddr() + "::Cookie::{"+cookie.getName()+","+cookie.getValue()+"}");
    			}
    		}
    		// pass the request along the filter chain
    		chain.doFilter(request, response);
    	}
    
    	public void destroy() {
    		//we can close resources here
    	}
    
    }
    
    
    package com.journaldev.servlet.filters;
    
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    @WebFilter("/AuthenticationFilter")
    public class AuthenticationFilter implements Filter {
    
    	private ServletContext context;
    	
    	public void init(FilterConfig fConfig) throws ServletException {
    		this.context = fConfig.getServletContext();
    		this.context.log("AuthenticationFilter initialized");
    	}
    	
    	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
    		HttpServletRequest req = (HttpServletRequest) request;
    		HttpServletResponse res = (HttpServletResponse) response;
    		
    		String uri = req.getRequestURI();
    		this.context.log("Requested Resource::"+uri);
    		
    		HttpSession session = req.getSession(false);
    		
    		if(session == null && !(uri.endsWith("html") || uri.endsWith("LoginServlet"))){
    			this.context.log("Unauthorized access request");
    			res.sendRedirect("login.html");
    		}else{
    			// pass the request along the filter chain
    			chain.doFilter(request, response);
    		}
    		
    		
    	}
    
    	public void destroy() {
    		//close any resources here
    	}
    
    }
    

    Notice that we are not authenticating any HTML page or LoginServlet. Now we will configure these filters mapping in the web.xml file.

    
    <?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
      <display-name>ServletFilterExample</display-name>
      <welcome-file-list>
        <welcome-file>login.html</welcome-file>
      </welcome-file-list>
      
      <filter>
        <filter-name>RequestLoggingFilter</filter-name>
        <filter-class>com.journaldev.servlet.filters.RequestLoggingFilter</filter-class>
      </filter>
      <filter>
        <filter-name>AuthenticationFilter</filter-name>
        <filter-class>com.journaldev.servlet.filters.AuthenticationFilter</filter-class>
      </filter>
      
      <filter-mapping>
        <filter-name>RequestLoggingFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
      </filter-mapping>
      <filter-mapping>
        <filter-name>AuthenticationFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    </web-app>
    

    Now when we will run our application, we will get response pages like below images.

    Servlet Filter Example

    Servlet Filter, Java Filter

    Servlet Filter Tutorial, Java Servlet Filter

    If you are not logged in and try to access any JSP page, you will be forwarded to the login page.

    In the server log file, you can see the logs written by servlet filters as well as servlets.

    
    Aug 13, 2013 1:06:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,B7275762B8D23121152B1270D6EB240A}
    Aug 13, 2013 1:06:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/
    Aug 13, 2013 1:06:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Unauthorized access request
    Aug 13, 2013 1:06:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,B7275762B8D23121152B1270D6EB240A}
    Aug 13, 2013 1:06:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/login.html
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Request Params::{pwd=password}
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Request Params::{user=admin}
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,B7275762B8D23121152B1270D6EB240A}
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/LoginServlet
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:06:43 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/LoginSuccess.jsp
    Aug 13, 2013 1:06:52 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:06:52 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:06:52 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/CheckoutPage.jsp
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/LogoutServlet
    JSESSIONID=8BDF777933194EDCAC1D8F1B73633C56
    User=Pankaj
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:07:00 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/login.html
    Aug 13, 2013 1:07:06 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/LoginSuccess.jsp
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Unauthorized access request
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{JSESSIONID,8BDF777933194EDCAC1D8F1B73633C56}
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: 0:0:0:0:0:0:0:1%0::Cookie::{user,admin}
    Aug 13, 2013 1:07:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Requested Resource::/ServletFilterExample/login.html
    

That’s all for Servlet Filter in java. It’s one of the important features of Java EE web application and we should use it for common tasks performed by various servlets. In future posts, we will look into servlet listeners and cookies.

Update: After getting a lot of requests for the downloadable project, I have attached it to the post, download it from the link below.

Check out next article in the series about Servlet Listener.

Update

Struts 2 uses Servlet Filter to intercept the client requests and forward them to appropriate action classes, these are called Struts 2 Interceptors. Check out Struts 2 Beginners Tutorial.

Comments

  1. Rajanikant says:

    Hi Pankaj,

    Nice article..
    I am trying to filter PROPFIND , TRACE , TRACK http-methods using filter , TRACK request easily filter out but PROPIND is still throwing 501 but i need 405 . here is my code .

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String method = httpRequest.getMethod();
    if (excludehttpmethodlist==”PROPFIND”) {
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.sendError(405);
    chain.doFilter(request, resp);
    } else {
    chain.doFilter(request, response);
    }

  2. Ameet says:

    Hi Pankaj,
    Very good article.
    I have one question inside doFilter method does HttpRequest.getParameter() returns value?

    What I’m trying is I have jsp page as follows:

    <form class="add_athlete" action="” method=”post” enctype=”multipart/form-data”>

    Following is the servlet code:

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;

    String action = req.getParameter(“type”);

    chain.doFilter(request, response);

    }

    Here request.getParamter() method should return type param value but it returns null value instead.
    It throws NullPointerException.

    1. Pankaj says:

      Do you have a variable with name as “type” in the form you are submitting? You can try to print all the request parameters and see if it’s missing?

      1. ameet says:

        Yes I have “type” as hidden input field in form.

        <form class="add_athlete" action="” method=”post” enctype=”multipart/form-data”>

  3. Mohit Patidar says:

    what does chain.doFilter(req, res) will do? could you please tell more about this. I understand it is chain of responsibility principal but i am not able to connect the dots here.

  4. Parth says:

    Hi Pankaj,

    I have a question, is it possible to store the login details of a user in a database by modifying the filter code? I actually want to use similar kind of web filter for one of my web services but I would like to store the log data as well.

    Any guidance in this matter would be highly appreciable.

    Thanks!
    Best regards,
    Parth

  5. Art says:

    Hi Pankaj! Thanks for Your post !

    I modified a little bit Your AuthenticationFilter.ja like that:

    if ( session == null && !( uri.endsWith(“login.jsp”) || uri.endsWith(“LoginServlet”) ) ){
    this.context.log(“Unauthorized access request”);
    res.sendRedirect(“login.jsp”);
    } else {
    chain.doFilter(request, response);
    }
    First time when i haven’t logged yet i tried to get access to some .jsp or .html file exclude login.jsp and this first request was redirected to login.jsp. But when i past the urs to browser again i got access to page. Si , i debugged and turned out that after first request a new session was created and after second click the “else” condition was executed.
    I guess there is a need for more complicated checking.

  6. Trabelsi chaima says:

    i didn t understand what is he use of the filter exactly
    and i want to know if the annotations you spoke about do you have to write them yourself or it just apear like the @override annotation could you anwser please

  7. Suxin says:

    Hi Pankaj,
    There is a bug in your authorization check. Your use login.html as the welcome page, so you should add the condition :
    !uri.endwith(“ServletFilterExample/”) to handle the url “localhost::8080/ServletFilterExample/”.

  8. Ron says:

    Is there a way to pass init parameters to a filter in the code rather than in xml?

    1. saurabh says:

      Yes by using annotation
      @WebServlet(initparams=@WebInitParam(name=”value”….)) write on top of servlet class which want to provide init params

      Cheers

  9. Andrey says:

    Dear Pankaj,

    thank you for a wonderful series of tutorials on Web Applications – Servlets- Filters.
    They are amazing

    Can you please explain why in the servlet you use
    response.sendRedirect(“LoginSuccess.jsp”); – in case authentication is successful
    and getServletContext().getRequestDispatcher(“/login.html”); – if authentication failed

    1. Hakim Pocketwalla says:

      Dear Andrey,

      In the case of LoginSuccess, we use response.redirect because we do not need to maintain the request and response objects. All we need to do is redirect to another page without having to show any kind of data related to the previous on the new page.

      But in the case of moving to Login.html, if you notice, we are also printing a message the the username or password is wrong. This is done with the help of a PrintWriter object that uses the response object. Therefore, here we will need to maintain the response object and we are sending data related to the previous page to the new page(The error message). Therefore,we use getServletContext().getRequestDispatcher as this maintains the request and response objects and forwards the request along with these objects. In comparision, response.sendRedirect does not maintain the request and response objects and the request is redirected as a complete new request.

  10. Jitendra says:

    This code will also filter image url and other css and js files. Which is bit more expensive for server

  11. Tip says:

    Thank you very much for each tutorial!
    I have a question: can you give an example on how to count unique users with Filter?
    Thank you!

  12. Enes says:

    easy and clear.

    Thanks.

  13. Decebal says:

    Thanks Pankaj for these tutorials related to Java Servlet. It’s not an easy job to explain with simple words about Java Servlet ecosystem.
    I believe that it’s difficult (in special for beginners) to create small and medium web applications in Java. Java comes with a lot of libraries/frameworks that allows you to create web applications but in my opinion all these are heavy for someone that are new in Java or for someone that wants to create a relative small applications. It’s overkill (code, knowledges, footprint) to use JSF, Vaadin, Spring (one some examples) to create a simple web application in Java.
    Are some nice such a frameworks (Expresss for NodeJs, Sinatra for Ruby, and I can continue with examples) but not in Java. In my opinion the Servlet API is to low to allow you to create a decent (in size and functionalities).
    For this reason, now two years ago, I initiated Pippo (http://pippo.ro). a Java micro web framework that brings some ideas from other non Java web frameworks.
    With Pippo, your web application is similar with a regular (non web) application with a static main method, so you can easy start and debug your application from your favorite IDE. The web container is a simple library (it’s embedded in application) and you can choose it (Jetty, Tomcat, Undertow, TJWS) via Maven dependencies.
    I don’t want to promote this framework here, all I want to say is that are good alternatives to “standard” Java web frameworks, alternatives that can help you.

    Thanks again Pankaj for your articles. I find these articles very useful.

  14. Jon Snow says:

    my company needed to fill out Residential Real Estate Lease this month and used an online platform that hosts lots of sample forms . If you require Residential Real Estate Lease as well , here’s a http://goo.gl/vuaer1

  15. Prashant Chaudhari says:

    Good example… Helped me Lot!!

  16. Selvaraj says:

    I ma having some issue in angular js and spring application.. when submitting request i m trying to modify the request using filter in web.xml.. request not invoking the filter its going directly.. can you help me to solve this.
    Thanks
    Selvaraj

  17. Rainer says:

    Hi Pankaj,
    Thanks for your great tutorials. BTW, can you please tell me, how to configure tomcat (8) in eclipse to see the logs written by filters and servlets? In ecslips console I can’t see these entries and there is also no server.log?
    Thanks, Rainer

  18. Akhil says:

    How the user is prevented from going back to the previous secured pages after log out in the code.I tried this code and after log out, if he press browser back button he can be able to view previously accessed pages.

  19. Getnet says:

    It’s an interesting tutorial but, my question is that after i logged out from the page and session expires, I can still go back to that page with browser back button. It will be pretty much better if you handle it.
    Thanks.

  20. Oleg says:

    You have mistake here “In this article, we will lean”. You have missed “r” in “learn”

  21. faisking says:

    how to add userId to response, and use that in another class?

  22. Abhishek says:

    I think you need to provide diagram to understand flow of execution.

  23. Jose Martinez says:

    Thank you for posting this.

  24. Rajesh Ingole says:

    Could please tell that on what basis the servletfilter is decided like at some time request is forwarded to RequestLoggingFilter and sometime to authenticationFilter ?

  25. Rajesh Ingole says:

    Could please tell that how come the server coming to know that he need to forward the request to AuthenticationFilter or RequestLoggingFilter ?

    1. Pankaj says:

      Check web.xml file for filter-mapping element, this is how we configure filters either by URL mapping or by servlet name.

  26. Haris says:

    Thank you Pankaj

  27. Ankit says:

    this tutorial is good ,but i know if we use annotation then we needs not to web.xml,simply apply the annotation on that we want to perform task like servlets,filters and using web.xml ,we can define filter chaining execution like f1,f2,f3 but if using annotations then how to execute these filtrs without web.xml

  28. sud says:

    tutorial is good, but back button still working. after logout and press back button not redirect to login page.

  29. Gokul Dhas says:

    Thank you Pankaj.

  30. Jonas says:

    Hi Pankaj,
    I’ve been reading your guides and they’re very good. Thanks.
    I just have one question about this tutorial. In AuthenticationFilter.java, is it really sufficient to check if req.getSession(false) returns null in order to determine authentication? Don’t you have to look at the session id or something?

    1. Pankaj says:

      If request doesn’t have session information, this call will not return any session object. So this ia the perfect way to check if request has valid session or not.

      1. Jonas says:

        Thanks, I just wanted to make sure. Keep up the good work!

  31. kiran says:

    after getting log list how to separate the individual log list??

  32. sudhir kumar says:

    Hi Pankaj,
    This example looks good, however you didn’t mention about the servlet you are using in your small demo project. In my project several servlets are used and the login/start page calling Controller Servlet. Before calling Controller servlet, i want my request should go through Filter. I made changes in web.xml and added Filter class but nothing work. Please note my servlet version was 2.2 therefore, i migrated my JDK version to 1.7. The code has been compiled in Websphere 8.5.5 application server

    xss
    com.CrossScriptingFilter

    xss
    /*

    Controller
    com.Controller
    1

  33. Vick says:

    Hi, thanks for your work and time, i am learning with this example and i have a question, mi actual web.xml looks like this:

    struts2

    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

    struts2
    /*

    my question is.. Do I have to change my settings for the one in your example or maybe both?; thanks a lot, have a nice day!

    1. Vick says:

      with respect to the above, and I put both settings above worked, now the problem is that the logout does not work, I added in the struts.xml two constants to exclude the application of method action, but can not be 2, for example:

        <- ->

      It’s one or the other but NOT both, may be happening? thank you very much!

      1. Vick says:

        constant name=”struts.action.excludePattern” value=”/LogoutServlet”/

        constant name=”struts.action.excludePattern” value=”/LoginServlet”/

        1. Vick says:

          Well, the solution was this line:

          constant name = “struts.action.excludePattern” value = “/ LoginServlet, / LogoutServlet” /

          Greetings … it was a pleasure!

  34. abd Erahim says:

    good work, well written code,
    Pankaj, if you don’t mind, This is a real world simple example that illustrates Java servlet filters, http://fivesnippets.blogspot.fr/2014/08/servlet-filter-for-ddos-spam-etc.html

    1. Pankaj says:

      The code in above link is not complete, there is no explanation and it’s certainly not helpful.

      1. abd Erahim says:

        OK, I’m really new to blogging, and this is probably my first blogging experience, so please would you like to review hints that I added to more explain the code, Thank you!

  35. Ajay says:

    Thanks dude..

    helped me 2 understand better

  36. Debanjan says:

    Hi Pankaj,
    Your article was extremely helpful. I am building a website where I have implemented filter to trap client requests and validate whether the user have login authorization. In my website there are static html pages that are outside the login portal which can be accessed by any user in the internet w/o login in.

    I’m using a servlet :”clientServlet” to handle all client requests and login. I want that when a user tries to access those static html pages, the filter shouldn’t trap the requests. Only requests from clients with a valid session/login should be able to access the internal contents(jsps). In this case should I use the : /clientServlet/* ? Is my understanding right?

    -Debanjan

  37. Karan says:

    Hi Pankaj,

    A very good article.
    However, i wanted to know, whether we can return (basically a String value) a value back from filter ?
    if yes, where can i get the return value ?

    Regards,
    Karan

    1. Pankaj says:

      As you can see from signature of doFilter() method, we can’t return anything from it. However you can set attributes in Request, Response etc and use them later on.

      1. Prasang Misra says:

        Hello Sir,
        Your article was very helpful,,
        but i have some problems implementing it in my project and would need your help

  38. Borat says:

    Hi Pankaj ! Actually, I tried to log your output to console also because I could not find the log file. Other than that, I changed my project structure a little. I have folders html and jsp inside web content. Obviously, I changed all the urls in my code accordingly. For example, login.html leads you to `/ServletFilterExample/LoginServlet` instead of `LoginServlet`.

    But, the main problem is that the Auth filter will not even let me login to the application. When I enter the correct user name and password, it lets me access the LoginServlet, but not the LoginSuccess.jsp page.
    What is the mistake I am making ? I think that the logic in this line of Auth Filter needs to be changed –
    session == null && !(uri.endsWith(“html”) || uri.endsWith(“LoginServlet”)).

    Thanks.

    1. Pankaj says:

      Yes, you are on right track. This line basically bypass all the static pages and Login page, if you have changed them then you need to make corresponding changes for auth filter too.

  39. borat says:

    As a beginner, this example looks too complicated to me. Can you please post a simple example for a filter ? Also, there are no comments for explaining how the code works. Also, please tell where the log files are saved and how to access them. I can’t find the log files generated by this line –
    this.context.log(req.getRemoteAddr() + “::Request Params::{” + name + “=” + value + “}”);

    1. Pankaj says:

      “Logging the request” – this is the least you will ever do from a filter, so I think both logging and authentication filter are good for most of the readers.

      For above logging, you will find it in the server.log file.

  40. bala says:

    can u please send one example in servlet for removing cross site scripting in URL.

  41. bala says:

    this filter is not working in weblogic server..
    anyone please reply.

    1. Pankaj says:

      are you getting any exceptions? Is the configuration same as above? Please provide weblogic server version too.

      1. bala says:

        weblogic 10.3

        1. bala says:

          i given this url

          http://localhost:7010/sampleStruts/login.html;location='http://www.google.com'

          after hitting request

          i got this

          http://localhost:7010/sampleStruts/login.html;%3Cscript%3Elocation='http://www.google.com'%3C/login.html

          how this is possible atually your redirect to login.html if uri not ends with (“html”) or (“LoginServlet”).please tell me why its not removing.

  42. Rakesh says:

    Something missing in your project! How to prevent to got logged in page after back button pressed?

    1. Pankaj says:

      Pressing back button doesn’t come to server, u need to rely on some other technologies for that.. such as JavaScript.

      1. Rakesh says:

        it can be made by JS .. but I did it with header nocache..!
        But this is a good article! keep posting!

  43. venu says:

    nice thank u..spend your valuble time with us

  44. Ashwin says:

    Hi..

    Can you please give an example on how to redirect to logout page when Session expires due to inactivity.

  45. Saul tobar says:

    Excellent tutorial, I’m interested to know how to do it for different user groups, ie, Administrator and Guest, when login with guest account and type the url in the browser does not possible access to the specific pages of the Administrator

  46. Aditya C says:

    Hi Pankaj

    can you please tell me what REQUEST do in filter mapping

    i am confused with that..

  47. Aditya C says:

    Thank you very much for each tutorial . you make all easy to understand by explaining code..

  48. Jawahar says:

    Hi Pankaj,

    I have been following most of your tutorials. It’s easy to understand. Thank you for your time. Keep up the good work.

    -Jawahar

    1. Pankaj says:

      Thanks Jawahar, I appreciate your comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages