Advertisment

Intercept Web Traffic in Java EE Web Apps

author-image
PCQ Bureau
New Update

Today the Web is dominated by the request/response architecture, wherein, a

client sends an HTTP protocol request for some action and the server, after

carrying out that action, responds with the HTTP response to the client. In this

series, we'll use the Interceptor Filter and Decorator design patterns to

intercept the incoming user requests and outgoing responses. The Intercepting

Filter pattern can be classified as a presentation tier pattern because it deals

with requests from the presentation tier. In this part, we'll leverage from

the Interceptor Filter pattern and then club it with the Decorator (Wrapper)

pattern in the second part.

Advertisment

The MVC pattern



Model View Controller or MVC is a popular Java EE design pattern used to
separate core business model functionality from the presentation and control

logic that uses this functionality. The business logic is carried out inside the

helper component (also called POJO beans). After getting the desired logic

implemented, the controller sets the result as a request/ session attribute, and

forwards the request to a view JSP page. Finally, the JSP view is responsible

for rendering the response back to the client. Consider the MVC model, as shown

in the figure below, that an existing application in production is using. 

Direct Hit!
Applies To:

Java EE developers



USP: Learn about pre- and post-process client Web request and
response with pluggable filters



Primary Link: http://tinyurl.com/4npo8




Google Keywords: Intercepting Filter, Java EE Design Patterns

The MVC pattern offers numerous advantages. These include multiple views that

use the same model components, easier support for new types of clients, enhanced

modularity and separation of concerts. Now consider this scenario-you want to

log every request made by a client. For logging the client request, a controller

is an excellent approach. That way, you are not writing the redundant logging

code in each component, rather you can factor out the common code in the

controller servlet. Consider another scenario where you have to provide a zipped

output after it's flushed from a JSP page, for improving the response time.

Here you have a problem in post-processing the response. Once the response is

flushed, your controller has no way of intercepting the response. Also, writing

the logic for zipping the output in every JSP page would not also kill

code-reuse but would also be difficult to maintain. Writing a plug-in or

plug-out type of component with the help of Interceptor Filter pattern that you

can fit anytime in your existing applications is easy and flexible.

Advertisment

Intercepting Filter to rescue



The Intercepting Filter, as the name suggests, intercepts the requests and helps
separate all the tasks that need to be done on the server into reusable



components. The actions/filters can be assigned to specific requests, chained in
any order, and added or removed within the application configuration. After the

filters complete, they pass the request to the intended recipient, which could

be any other Web component like a Servlet, JSP or even another chained filter.

After the request processing chain is finished, a response is sent to the client

(see the following diagram).

Servlet Filter



Servlet Filters, introduced with servlet specification version 2.3, help in
implementing the Interceptor Filter pattern. A servlet filter is a small class

that allows you to manipulate the request and/or response. A filter object is

instantiated and managed by the servlet container, and has a lifecycle similar

to a servlet. Common uses for filters include logging HTTP requests, validating

request parameters and authorizing or denying access to resources.

Advertisment

Implementing a log filter



Implementing filters in Java EE is a three-step process. You begin by creating a
filter implementation class, declaratively add filter to the deployment



descriptor file, and finally, deploy the filter. Servlet filters must implement
the javax.servlet.

Filter interface, and override some container callback methods, as shown in

the following code segment.

package com.pcquest.tracker;



import java.io.IOException;


import javax.servlet.*;


import javax.servlet.http.*;


public class LogFilter implements Filter {


private FilterConfig filterConfig;



Advertisment

public void init(FilterConfig config) throws

ServletException {



this.filterConfig=config;


}


public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc)
throws IOException, ServletException{



String uri = "";


if (req instanceof HttpServletRequest) {


uri = ((HttpServletRequest)req).getRequestURI();


}


String remoteHost=req.getRemoteHost();






// log incoming user



if(remoteHost!=null)


filterConfig.getServletContext().log("Remote Host "+ remoteHost+
" trying to access "+ uri);

//invoke next component in the request

procesing chain



fc.doFilter(req,res);


}


public void destroy() {


// cleanup code


}


}




Advertisment

The filter begins its life when the init()method is called. When the

container loads the filter for the first time, the init() method is called. This

method is called just once by the Web container to indicate to a filter that it

is being placed into service. The class obtains a reference to a FilterConfig

object inside the init() method.

Next, the doFilter() method of the filter is called by the container, passing

in references to the ServletRequest, ServletResponse, and FilterChain



objects. In our example, inside the doFilter() method, we are logging the remote
host's IP and the requested URI. Finally, the destroy() method is called by

the Web container to indicate to a filter that it is being taken out of service.

This is the logged output

produced from logging the incoming client request
Advertisment

Configuring filters



Java EE filters are configured declaratively in the deployment descriptor-
web.xml file. The following code segment defines the LogFilter via the

tag and then maps it to a URL pattern through the

element.





Log Filter


com.pcquest.tracker.LogFilter











Log Filter


/*





The one, /* maps all resources in the Web application to the defined filters.

This is a typical mapping declaration for a controller component. This way, a

filter can also be mapped to a JSP page. Deploying filters is easy. The filter

implementation class is packaged in the WAR (Web ARchive) along with the static

content and servlets that make up the Web application. The output produced from

logging the incoming client request is shown in the figure on the previous page.

Conclusion



Servlet filters are modular, reusable and portable web components that are
flexibly declared via XML tags in the deployment descriptor file. In this part

we looked at a way of preprocessing on the request before it enters the Web

tier. In the second part, we'll use the Decorator design pattern to implement

a customized response wrapper, which can be used for post-processing in a

filter.

Advertisment