J2EE Design Pattern : Presentation Tier Patterns : Intercepting Filter Design Pattern
Intercepting Filter Design Pattern |
Intercepting Filter facilitates pre-processing and post-processing of a request
Interceptor Pattern can be Use for
- Authentication
- Access Validation
- System Logging
- System Debugging
- Data Encoding
- Browser Trapping
- Response Filtering
Problem
Pre-processing and post-processing of a client Web request and response are required to be done. When a request enters a Web application, it often must pass several entrance tests prior to the main processing stage for that various components are added. For example,
- Has the client been authenticated?
- Does the client have a valid session?
- What is the client’s IP address from a trusted network?
- Does the request path violate any constraints?
- What encoding does the client use to send the data?
- Do you support the browser type of the client?
Context
The presentation-tier request handling mechanism receives many different requests, which must be modified, audited, or uncompressed before being further processed.
Solution
These problems are solved by processing with a variety of common services, such as security, logging, debugging, and so forth. These filters are components that are independent of the main application code and they may be added or removed declaratively.
Non-software Intercepting Example
Intercepting Filter Class Diagram
Participants and Responsibilities
FilterManager
The FilterManager manages filter processing. It creates the FilterChain with the appropriate filters, in the correct order, and initiates processing.
FilterChain
The FilterChain is an ordered collection of independent filters.
FilterOne, FilterTwo, FilterThree
These are the individual filters that are mapped to a target. The FilterChain coordinates their processing.
Target
The Target is the resource requested by the client.
Example of Intercepting Filter |
EncodingFilter.java
public class EncodingFilter implements Filter {
private FilterConfig config = null;
// default to ASCII
private String targetEncoding = "ASCII";
public void init(FilterConfig config) throws ServletException {
this.config = config;
this.targetEncoding = config.getInitParameter("encoding");
}
public void destroy() {
config = null;
targetEncoding = null;
}
public void doFilter(ServletRequest srequest, ServletResponse sresponse,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)srequest;
request.setCharacterEncoding(targetEncoding);
// move on to the next
chain.doFilter(srequest,sresponse);
}
}
code for web.xml
<filter>
<filter-namer>EncodeFilter</filter-namer>
<display-namer>EncodeFilter</display-namer>
<description></description>
<filter-class>encodefilter.EncodeFilter</filter-class>
</filter>
<filter-mapping>
<filter-namer>EncodeFilter</filter-namer>
<url-pattern>/* <url-pattern>
</filter-mapping>
Recent Comments