Showing posts with label Servlet Filter. Show all posts
Showing posts with label Servlet Filter. Show all posts

Java Servlet Filter Example2


TimerFilter

package com.informit.webtechnologies;

import javax.servlet.*;

public class TimerFilter implements Filter
{
   private FilterConfig config;

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

   public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
              throws java.io.IOException, ServletException
   {
      // Record the start time of the request
      long before = System.currentTimeMillis();

      // Invoke the Servlet
      chain.doFilter( req, res );

      // Capture the end time of the request
      long after = System.currentTimeMillis();
 
      // Display the elapsed time to the standard output
      System.out.println("Elapsed Time: " + ( after - before ) + "ms" );   
   }

   public void destroy()
   {
      this.config = null;
   }
}
The focus of the TimerFilter class is the doFilter() method; the init and destroy methods manage an internal FilterConfig member variable that is not used in this example. ThedoFilter() method records the start time that the filter is invoked, executes the rest of the filter chain, and then captures the end time of the request to display the elapsed time to the standard output.
The functionality of this filter is simple, but how do we hook it up to intercept Servlets? The answer is by modifying the web deployment descriptor. In the Servlet 2.3 specification, the following two sections were added to web deployment descriptor that parallel the Servlet descriptors:
  • filter: defines a unique filter name and the fully qualified class name that it references
  • filter-mapping: maps URLs to filters
So in this example we add the following to the beginning of the web.xml file:
<filter>
  <filter-name>TimerFilter</filter-name>
  <filter-class>com.informit.webtechnologies.TimerFilter</filter-class>
</filter>
<filter-mapping> <filter-name>TimerFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
This defines a TimerFilter as being implemented by thecom.informit.webtechnologies.TimerFilter class and matching all URLs in our web application (by matching the URL pattern “/*”.) So the complete web.xml file is shown in listing 2.

Listing 2. Filter example’s web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
                            "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>
  <filter>
    <filter-name>TimerFilter</filter-name>
    <filter-class>com.informit.webtechnologies.TimerFilter</filter-class>
  <filter-mapping>

  <filter-mapping>
    <filter-name>TimerFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <servlet>
    <servlet-name>MyHelloServlet</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>MyHelloServlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>
Build your WAR file as usual and drop the TimerFilter.class file in the /WEB-INF/classes/com/informit/webtechnologies directory. Deploy your WAR file to your Servlet container, and then watch the output. The following is sample output when deploying this WAR file to Jetty running inside JBoss:
00:49:57,382 INFO [STDOUT] Elapsed Time: 10ms
00:49:57,382 INFO [STDOUT] Elapsed Time: 0ms
00:49:57,382 INFO [STDOUT] Elapsed Time: 0ms
00:49:57,382 INFO [STDOUT] Elapsed Time: 10ms
00:49:57,382 INFO [STDOUT] Elapsed Time: 0ms
00:49:57,382 INFO [STDOUT] Elapsed Time: 10ms

Summary

This has been a brief introduction to using Servlet Filters. You can define multiple filters for the same URLs to accomplish tasks such asadding additional logging, implementing authentication and security, and timing requests, just to name a few. In an advanced implementation of filters you might perform XSLT or other transformations to convert content generated in your Servlet for presentation to specific output devices (such as mobile devices.) I hope this will inspire you to experiment with filters and pick up a good book on Servlets that will take you further.

Java Servlet Filter Example1


The filters in deployment descriptor:
<web-app>
	<filter>
		<filter-name>MyFilter</filter-name>
		<filter-class>subin.rnd.enterprise.filter.MyFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>MyFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>MyFilter</filter-name>
		<servlet-name>MyServlet</servlet-name>
		<dispatcher>REQUEST</dispatcher>
	</filter-mapping>
</web-app>
We can have a filter (or a chain of filters) processing the request/response. In the above descriptor, we are linking a filter for a URL pattern as well as for a specific servlet. So in the above case, for MyServlet, the filter will get executed twice as we have mapped the filter MyFilter to all URLs and for MyServlet. So the order of execution will be MyFilter.doFilter() > MyFilter.doFilter() > MyServlet.doGet().
MyServlet.java
01import javax.servlet.ServletException;
02import javax.servlet.http.HttpServlet;
03import javax.servlet.http.HttpServletRequest;
04import javax.servlet.http.HttpServletResponse;
05
06public class MyServlet
07extends HttpServlet
08{
09  @Override
10  public void doGet(HttpServletRequest request,
11    HttpServletResponse response)
12  throws ServletException
13  {
14    System.out.println("doGet()");
15    response.setContentType("text/plain");
16    ServletUtility.write(response, "Hello world!".getBytes());
17  }
18}
MyFilter.java
01import java.io.IOException;
02import javax.servlet.Filter;
03import javax.servlet.FilterChain;
04import javax.servlet.FilterConfig;
05import javax.servlet.ServletException;
06import javax.servlet.ServletRequest;
07import javax.servlet.ServletResponse;
08import javax.servlet.http.HttpServletResponse;
09
10public class MyFilter
11implements Filter
12{
13  public void destroy()
14  {
15  }
16
17  public void doFilter(ServletRequest request, ServletResponse response,
18     FilterChain filterChain)
19  throws IOException, ServletException
20  {
21     System.out.println("doFilter()");
22
23     ByteStreamResponseWrapper responseWrapper = null;
24     byte[] responseAsBytes = null;
25     String processedResponse = null;
26
27     // Creating a response wrapper
28     responseWrapper = new ByteStreamResponseWrapper(
29        (HttpServletResponse) response);
30     filterChain.doFilter(request, responseWrapper);
31
32     // Process the response
33     processedResponse = responseWrapper.toString();
34     if (null != processedResponse)
35     {
36       processedResponse = processedResponse.toUpperCase();
37       responseAsBytes = processedResponse.getBytes();
38     }
39
40     // Writing the response (as bytes) to the servlet output stream
41     ServletUtility.write(response, responseAsBytes);
42  }
43
44  public void init(FilterConfig filterConfig)
45  throws ServletException
46  {
47    // We can initialize a filter using the init-params here
48    // (which we defined in the deployment descriptor - web.xml)
49  }
50}
Other filesThere are two more Java files – ByteStreamResponseWrapper & ServletUtility.ByteStreamResponseWrapper is an extension ofjavax.servlet.http.HttpServletResponseWrapper with some methods – toString(),getOutputStream() & getWriter() – overriden. ServletUtility is a utility class to write a byte stream to the servlet output stream.
OutputThe “Hello world!” from MyServlet is filtered to “HELLO WORLD!”  by MyFilter.
Fig: Output in browser
Output
Fig: Jboss console output
Jboss Console output



Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email