What are Filters in Java J2EE applications.

Points To Remember
  • A filter is hit before the servlet or a controller is hit and before the response is sent back to the client.
  • Filters can be used to apply some action on application level.
  • A filter implements the javax.servlet.Filter interface and the primary filter functionality is implemented by the doFilter() method of the filter.
  • Filters can be used to manipulate both requests from client and response from server.
What is a Filter in Java Web Applications ?
A filter is a useful way of performing filtering operations in java web applications bith before a request reaches the backend server and after the response is received from the backend server. A filter is basically used to filter things. Suppose you want to make your application accessible to a particular country, then you can apply IP filtering in your application, similarly we can have various types of filters like
  • Authentication Filters
  • Data compression Filters
  • Encryption Filters
  • Filters that trigger resource access events
  • Image Conversion Filters
  • Logging and Auditing Filters
  • MIME-TYPE Chain Filters
  • Tokenizing Filters
  • XSL/T Filters That Transform XML Content
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in your application's deployment descriptor. When the web container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.

Example : Implementation of a Filter 

web.xml -

It contains the following
  • Welcome file list
  • Mapping for a filter named MyFilter
  • Mapping for a servlet named DemoServlet
<web-app id="WebApp_ID" version="2.5" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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_2_5.xsd">
  <display-name>FilterDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>com.ekiras.filter.MyFilter</filter-class>
    <init-param>
      <param-name>my-param</param-name>
      <param-value>my-param-value</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
    <description></description>
    <display-name>DemoServlet</display-name>
    <servlet-name>DemoServlet</servlet-name>
    <servlet-class>com.ekiras.servlet.DemoServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DemoServlet</servlet-name>
    <url-pattern>/DemoServlet</url-pattern>
  </servlet-mapping>
</web-app>

Filter - MyFilter

This filter implements the Filter interface and overrides its methods init(), destroy() and doFilter(). We write the filtering logic in the doFilter() method. In this case we are just going to add the init parameters for the filter to the response object inorder to show it on the jsp. filterChain.doFilter() method will take the control to the requested servlet or jsp. After a response has been set the control comes back to this filter.

package com.ekiras.filter;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

// Implements Filter class
public class MyFilter implements Filter {

	// To get The FilterConfig object
	FilterConfig filterConfig = null;

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public void destroy() {
	}
    
	//doFilter() method is the method where we write filtering logic.
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		servletResponse.setContentType("text/html");
		
		PrintWriter out = servletResponse.getWriter();
                // Get init parameter 
		out.println("my-param (InitParameter): " + filterConfig.getInitParameter("my-param"));
		out.println("

Parameters:
");
		Enumeration parameterNames = servletRequest.getParameterNames();
		if (parameterNames.hasMoreElements()) {
			while (parameterNames.hasMoreElements()) {
				String name = parameterNames.nextElement();
				String value = servletRequest.getParameter(name);
				out.println("name:" + name + ", value: " + value + "
");
			}
		} else {
			out.println("---None---
");
		}
		out.println("
Start Regular Content:

"); // Pass request back down the filter chain filterChain.doFilter(servletRequest, servletResponse); out.println("
End Regular Content: "); } }

Servlet - DemoServlet

This is a demo servlet and just calls a method performTask() to print a demo message.
package com.ekiras.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public DemoServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		performTask(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		performTask(request, response);
	}

	private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("TestServlet says hi");
	}

}

Jsp - index.jsp

This is the jsp that will be hit. This jsp just contains a demo message .
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1">;

<html>
<head>

<title>Test Filter</title>
</head>
<body>
Hi This is My JSP
</body>
</html>

No comments:

Powered by Blogger.