package net.viralpatel.servlet.filters;
import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class LogFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
//Get the IP address of client machine.
String ipAddress = request.getRemoteAddr();
//Log the IP address and current timestamp.
System.out.println("IP "+ipAddress + ", Time "
+ new Date().toString());
chain.doFilter(req, res);
}
public void init(FilterConfig config) throws ServletException {
//Get init parameter
String testParam = config.getInitParameter("test-param");
//Print the init parameter
System.out.println("Test Param: " + testParam);
}
public void destroy() {
//add code to release any resource
}
}
Code language: Java (java)
In this filter example, we have implemented an interface javax.servlet.Filter and override its methods init, doFilter and destroy. The init() method is used to initialize any code that is used by Filter. Also note that, init() method will get an object of FilterConfig which contains different Filter level information as well as init parameters which is passed from Web.xml (Deployment descriptor). The doFilter() method will do the actual logging of information. You can modify this method and add your code which can modify request/session/response, add any attribute in request etc. The destroy() method is called by the container when it wants to garbage collect the filter. This is usually done when filter is not used for long time and server wants to allocate memory for other applications. <filter>
<filter-name>LogFilter</filter-name>
<filter-class>
net.viralpatel.servlet.filters.LogFilter
</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>This parameter is for testing.</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Code language: HTML, XML (xml)
In this entry, we have added LogFilter class in Web xml and mapped it with URL /*. Hence any request from client will generated a call to this filter. Also we have passed a parameter test-param. This is just to show how to pass and retrieve a parameter in servlet filter. Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
Thanks for this guide! It made it VERY easy to get a quick servlet filter up and running to play around!
Thanks for a simple yet illustratice explaination
Excelent!!! it's very usefull.
thanks...
Uh, for the neophyte, what if after setting up this project, entering the code, etc. the launch (http://localhost:8080/ServletFilterProject/) produces only a 404? (Eclipse 3.3.2, WST 2.0.2)
Hi Russell,
I am not sure about the error, but it seems that something is wrong hence your browser is not able to get anything (resource not found!!). Can you try running http://localhost:8080 and check what is coming? Also check if your context root is properly set.
thank you viral,
it is ery easy and helpful for me.
@balveer: you welcome. feel free to bookmark this site or registered your email to get articles via email :)
Thanks, this was quite useful. I think I know what problem Russell was encountering:
The package is set to \"net.viralpatel.servlet.filters\" but in the mapping it\'s trying to find the class \"net.viralpatel.servlet.filter.LogFilter\". If you go into web.xml and add an s to \"filter\" so that it says \"net.viralpatel.filters.LogFilter\" then you should actually get a printout in the console. Otherwise it\'ll throw class not found exception.
Nice article.
You may wanted to check some similar articles below:
http://www.tech-freaks.in/Java-Programming/JSP-Servlets/jsp-servlet-workshop.html
http://www.stage3.tech-freaks.in/Java-Programming/JSP-Servlets/eclipse-tomcat-integration.html
It's so nice to find simple blogs that are easy to understand. Nice job, Viral. I will be looking through the remainder of your blogs in hopes to learn more techniques.