Tutorial

Java Servlet Filter Example Tutorial

Published on August 3, 2022
author

Pankaj

Java Servlet Filter Example Tutorial

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

  6. 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.

  7. 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.
  8. 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

  9. 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.

  10. 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](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/08/Servlet-Filter-Example-Project.png)](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/08/Servlet-Filter-Example-Project.png) 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" "https://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" "https://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="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://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](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/08/Servlet-Filter-Login-450x141.png)](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/08/Servlet-Filter-Login.png) [![Servlet Filter, Java Filter](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/08/Servlet-Filter-Login-Success-450x229.png)](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/08/Servlet-Filter-Login-Success.png) [![Servlet Filter Tutorial, Java Servlet Filter](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/08/Servlet-Filter-Checkout-450x181.png)](https://journaldev.nyc3.cdn.digitaloceanspaces.com/2013/08/Servlet-Filter-Checkout.png) 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.

Download Servlet Filter Example Project

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 14, 2013

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

- Jawahar

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 14, 2013

Thanks Jawahar, I appreciate your comment.

- Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 29, 2013

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

    - Aditya C

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 1, 2013

      Hi Pankaj can you please tell me what REQUEST do in filter mapping i am confused with that…

      - Aditya C

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        February 5, 2014

        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

        - Saul tobar

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 24, 2014

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

          - Ashwin

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            March 21, 2014

            nice thank u…spend your valuble time with us

            - venu

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 12, 2014

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

              - Rakesh

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 12, 2014

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

              - Pankaj

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 14, 2014

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

              - Rakesh

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                April 28, 2014

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

                - bala

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                April 28, 2014

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

                - Pankaj

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                May 7, 2014

                weblogic 10.3

                - bala

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                May 7, 2014

                i given this url https://localhost:7010/sampleStruts/login.html;location='https://www.google.com' after hitting request i got this https://localhost:7010/sampleStruts/login.html;%3Cscript%3Elocation='https://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.

                - bala

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  May 7, 2014

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

                  - bala

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 25, 2014

                    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 + “}”);

                    - borat

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 26, 2014

                    “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.

                    - Pankaj

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      May 26, 2014

                      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.

                      - Borat

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      May 26, 2014

                      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.

                      - Pankaj

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        June 5, 2014

                        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

                        - Karan

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        June 5, 2014

                        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.

                        - Pankaj

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        July 25, 2014

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

                        - Prasang Misra

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          June 7, 2014

                          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

                          - Debanjan

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            July 24, 2014

                            Thanks dude… helped me 2 understand better

                            - Ajay

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              August 7, 2014

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

                              - abd Erahim

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              August 7, 2014

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

                              - Pankaj

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              August 7, 2014

                              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!

                              - abd Erahim

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                August 14, 2014

                                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!

                                - Vick

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                August 14, 2014

                                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!

                                - Vick

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                August 14, 2014

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

                                - Vick

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                August 15, 2014

                                Well, the solution was this line: constant name = “struts.action.excludePattern” value = “/ LoginServlet, / LogoutServlet” / Greetings … it was a pleasure!

                                - Vick

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  October 7, 2014

                                  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

                                  - sudhir kumar

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    October 13, 2014

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

                                    - kiran

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      October 29, 2014

                                      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?

                                      - Jonas

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      October 30, 2014

                                      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.

                                      - Pankaj

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      October 30, 2014

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

                                      - Jonas

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        November 7, 2014

                                        Thank you Pankaj.

                                        - Gokul Dhas

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          November 16, 2014

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

                                          - sud

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            November 26, 2014

                                            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

                                            - Ankit

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              January 6, 2015

                                              Thank you Pankaj

                                              - Haris

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                February 1, 2015

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

                                                - Rajesh Ingole

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                February 1, 2015

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

                                                - Pankaj

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  February 1, 2015

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

                                                  - Rajesh Ingole

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    February 18, 2015

                                                    Thank you for posting this.

                                                    - Jose Martinez

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      May 21, 2015

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

                                                      - Abhishek

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        June 14, 2015

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

                                                        - faisking

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          June 20, 2015

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

                                                          - Oleg

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            June 23, 2015

                                                            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.

                                                            - Getnet

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              July 3, 2015

                                                              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.

                                                              - Akhil

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                July 14, 2015

                                                                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

                                                                - Rainer

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  November 21, 2015

                                                                  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

                                                                  - Selvaraj

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    June 30, 2016

                                                                    Good example… Helped me Lot!!

                                                                    - Prashant Chaudhari

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      September 8, 2016

                                                                      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 https://goo.gl/vuaer1

                                                                      - Jon Snow

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        December 10, 2016

                                                                        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 (https://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.

                                                                        - Decebal

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          March 21, 2017

                                                                          easy and clear. Thanks.

                                                                          - Enes

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            May 2, 2017

                                                                            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!

                                                                            - Tip

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              May 19, 2017

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

                                                                              - Jitendra

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                August 21, 2017

                                                                                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

                                                                                - Andrey

                                                                                  Try DigitalOcean for free

                                                                                  Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                                  Sign up

                                                                                  Join the Tech Talk
                                                                                  Success! Thank you! Please check your email for further details.

                                                                                  Please complete your information!

                                                                                  Become a contributor for community

                                                                                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                                  DigitalOcean Documentation

                                                                                  Full documentation for every DigitalOcean product.

                                                                                  Resources for startups and SMBs

                                                                                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                                  Get our newsletter

                                                                                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                                  New accounts only. By submitting your email you agree to our Privacy Policy

                                                                                  The developer cloud

                                                                                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                                  Get started for free

                                                                                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                                  *This promotional offer applies to new accounts only.