Searching...
Monday, 1 October 2012

Servlet Filter Example

11:29

What is Servlet Filter?

Servlet filter specification enabling you to intercept a request before it reaches a resource. In other words, a filter gives you access to the HttpServletRequest and the HttpServletResponse objects before they are passed in to a servlet.

Servlet Filter API

Servlet Filter specification has the following three interfaces in the javax.servlet
•  Filter
•  FilterConfig
•  FilterChain

The Filter Interface

javax.servlet.Filter is  the main interface that needs to be implement when writing a filter.  Below are the  life cycle of a filter is represented by this interface's three methods (Below methods) 
public void init(FilterConfig filterConfig)
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
public void destroy()


The FilterConfig Interface

A FilterConfig object represents the configuration for the filter. This object allows you to obtain
the ServletContext object and pass initialization values to the filter through its initial  parameters, which you define in the web.xml

The FilterChain Interface

A  FilterChain object is passed in by the servlet container to the doFilter method of the filter class. Filters use the FilterChain object to invoke the next filter in the chain, or, if the filter is the last in the chain, to invoke the next resource (servlet) which we mentioned in the action.

Example

A user name password form needs to be submit to one servlet, and there is an implementation of a Filter before reaching to the servlet and check the username is admin or not also printing the ip address of the request.
Jsp file which accept username and password (NewFile.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here....</title>
</head>
<body>
    <form name="input" action="http://localhost:8081/MyFirstServlet"
        method="get">
        User name: <input type="text" name="user"> Password: <input
            type="text" name="pass"> <input type="submit" value="Submit">
    </form>
</body>
</html>

Servlet Filter class

package com.vinod;

import java.io.IOException;
import java.io.PrintWriter;
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 MyServletFilter
 */

public class MyServletFilter implements Filter {

    /**
     * Default constructor.
     */

    public MyServletFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */

    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       
        System.out.println("Filter triggered");
        System.out.println("IP " + request.getRemoteAddr() + ", Time "
                     + new Date().toString());
        if (request.getParameter("user")!=null&&!request.getParameter("user").equals("admin")) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<HTML><TITLE>Http Servlet Example</TITLE><BODY>");
            out.println("<h3>You are not authorized to login</h3><HR>");
            out.println("</BODY><HTML>");
            out.close();
     } else {
            chain.doFilter(request, response);

     }  }

    /**
     * @see Filter#init(FilterConfig)
     */

    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}

My Servlet class

package com.vinod;

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;

/**
 * Servlet implementation class MyFirstServlet
 */

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

    /**
     * Default constructor.
     */

    public MyFirstServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<HTML><TITLE>Http Servlet Example</TITLE><BODY>");
        out.println("<h3>Hello world</h3><HR>");
        out.println("</BODY><HTML>");
        out.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
  

Web.xml

<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_2_5.xsd"
    id="WebApp_ID" version="2.5">
        <display-name>Archetype Created Web Application</display-name>
        <filter>
            <description>
            </description>
            <display-name>MyServletFilter</display-name>
            <filter-name>MyServletFilter</filter-name>
            <filter-class>com.vinod.MyServletFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>MyServletFilter</filter-name>
            <url-pattern>/MyFirstServlet</url-pattern>
        </filter-mapping>
        <servlet>
            <servlet-name>MyFirstServlet</servlet-name>
            <servlet-class>com.vinod.MyFirstServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>MyFirstServlet</servlet-name>
    <url-pattern>/MyFirstServlet</url-pattern>      </servlet-mapping>
    </web-app>

Deploy and run the application, in this example i am using jetty server and using  jetty:run command to start
http://localhost:8081/NewFile.jsp


Download example

0 comments: