In this tutorial we are going to see about Servlet Filter with example program.
A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.
Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, and a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.
Filters are configured in the deployment descriptor of a web application.
Types of Filter used for specified purpose
The Filter is Java class which implement javax.servlet.Filter interface.
Now see the example program.
1. Create new Dynamic web project by choosing File –> New –> Dynamic Web Project .
2. Create the Project called ServletExample as given below.
3. Create package called com.javatutorialscorner.servlet under ServletExample.
4. Create Filter called FilterExample as shown in figure.
5. Click Next it will show URL mapping.You can edit Filter URL if you need.
6. Create Servlet called HelloWorld.
7. By default your Filter, Servlet will be mapped in web.xml, if your Filter, and Servlet not mapped in your web.xml use the following configuration to map the Filter and Servlet in your web.xml
Filter Mapping
Servlet Mapping
web.xml
URL patteren Mapped as /* , so Filter will be called for each request and response.
8. Add the required code inside service() method.
FilterExample.java
HelloWorld.java
9. Now save and Run the Program, Run As –> Run on Server – Select your web Server to run the servlet. ( see How to configure tomcat in eclipse)
http://www.javatutorialcorner.com/2014/03/how-to-configure-tomcat-in-eclipse.html
Filter will be called when Tomcat started, because URL pattern of filter is mapped as /*
10.call the following URL .
http://localhost:8080/ServletExample/HelloWorld
Output
IP Address xxx.x.x.xx, Time Sun Apr 13 06:45:48 IST 2014
IP Address xxx.x.x.xx, Time Sun Apr 13 06:46:01 IST 2014
Inside HelloWorld Servlet
A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.
Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, and a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.
Filters are configured in the deployment descriptor of a web application.
Types of Filter used for specified purpose
- Authentication Filters
- Logging and Auditing Filters
- Image conversion Filters
- Data compression Filters
- Encryption Filters
- Tokenizing Filters
- Filters that trigger resource access events
- XSL/T filters
- Mime-type chain Filter
The Filter is Java class which implement javax.servlet.Filter interface.
S.NO |
Methods with Description
|
1 | void init(FilterConfig filterConfig) throws ServletException Called by the web container to indicate to a filter that it is being placed into service. The servlet container calls the init method exactly once after instantiating the filter. The init method must complete successfully before the filter is asked to do any filtering work. The web container cannot place the filter into service if the init method either 1. Throws a ServletException 2. Does not return within a time period defined by the web container |
2 | void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws java.io.IOException,ServletException The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain. A typical implementation of this method would follow the following pattern: 1. Examine the request 2. Optionally wrap the request object with a custom implementation to filter content or headers for input filtering 3. Optionally wrap the response object with a custom implementation to filter content or headers for output filtering 4. Either invoke the next entity in the chain using the FilterChain object (chain.doFilter()), or not pass on the request/response pair to the next entity in the filter chain to block the request processing 5. Directly set headers on the response after invocation of the next entity in the filter chain. |
3 | void destroy() Called by the web container to indicate to a filter that it is being taken out of service. This method is only called once all threads within the filter's doFilter method have exited or after a timeout period has passed. After the web container calls this method, it will not call the doFilter method again on this instance of the filter. This method gives the filter an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the filter's current state in memory. |
1. Create new Dynamic web project by choosing File –> New –> Dynamic Web Project .
2. Create the Project called ServletExample as given below.
3. Create package called com.javatutorialscorner.servlet under ServletExample.
4. Create Filter called FilterExample as shown in figure.
5. Click Next it will show URL mapping.You can edit Filter URL if you need.
6. Create Servlet called HelloWorld.
7. By default your Filter, Servlet will be mapped in web.xml, if your Filter, and Servlet not mapped in your web.xml use the following configuration to map the Filter and Servlet in your web.xml
Filter Mapping
<filter> <filter-name>Name of Filter</filter-name> <filter-class>Fully Qualified Filter Class</filter-class> </filter> <filter-mapping> <filter-name>Name of Filter</filter-name> <url-pattern>/URL Pattern for Filter</url-pattern> </filter-mapping>
Servlet Mapping
<servlet> <servlet-name>Your Servlet Name</servlet-name> <servlet-class>Fully Qulaified Servlet Class Name</servlet-class> </servlet> <servlet-mapping> <servlet-name>Your Servlet Name</servlet-name> <url-pattern>/URL to Call Servlet</url-pattern> </servlet-mapping>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>ServetExample</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <filter> <filter-name>FilterExample</filter-name> <filter-class>com.javatutorialscorner.servlet.FilterExample</filter-class> </filter> <filter-mapping> <filter-name>FilterExample</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>com.javatutorialscorner.servlet.HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app>
URL patteren Mapped as /* , so Filter will be called for each request and response.
8. Add the required code inside service() method.
FilterExample.java
package com.javatutorialscorner.servlet; 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; /** * Servlet Filter implementation class FilterExample */ public class FilterExample implements Filter { /** * Default constructor. */ public FilterExample() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub // Called befor Filter instance Instance removed from service by web // container } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here String ip = request.getRemoteAddr(); System.out.println("IP Address" + ip + ", Time " + new Date().toString()); // pass the request along the filter chain chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub // called first time of Filter loads you can do your initialization // config here. // like read init param, load property,etc } }
HelloWorld.java
package com.javatutorialscorner.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; /** * Servlet implementation class HelloWorld */ public class HelloWorld extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger log = Logger.getLogger(HelloWorld.class); /** * @see HttpServlet#HttpServlet() */ public HelloWorld() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("Inside HelloWorld Servlet"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
9. Now save and Run the Program, Run As –> Run on Server – Select your web Server to run the servlet. ( see How to configure tomcat in eclipse)
http://www.javatutorialcorner.com/2014/03/how-to-configure-tomcat-in-eclipse.html
Filter will be called when Tomcat started, because URL pattern of filter is mapped as /*
10.call the following URL .
http://localhost:8080/ServletExample/HelloWorld
Output
IP Address xxx.x.x.xx, Time Sun Apr 13 06:45:48 IST 2014
IP Address xxx.x.x.xx, Time Sun Apr 13 06:46:01 IST 2014
Inside HelloWorld Servlet
0 comments:
Post a Comment