Learn Java for Web Development

(Tina Meador) #1

148 CHAPTER 3: Best Practices in Java EE Web Development


The Intercepting Filter pattern is used for preprocessing and postprocessing of client requests and
also the responses by intercepting requests and responses. The filters are pluggable in the sense
that you can add or remove them without changing the code.


One of the use cases for which the Intercepting Filter pattern is deemed best fit is when you want
to enable theIE9 document mode of the browser by default. IE has two modes: browser mode and
document mode. The browser always sends browser mode data to the server, and the server always
responds with document mode data. The browser mode data consists of a user agent string with
a version and trident token information, while the document mode data consists of metatags that
dictate the mode in which the response will be rendered on the browser.


Listing 3-57 shows a simple response filter that enables the IE9 document mode of the browser
by default.


Listing 3-57. Simple Response Filter


1.package com.apress.filters
2.import javax.servlet.*;
3.import javax.servlet.http.HttpServletResponse;
4.import java.io.IOException;
5.import java.util.Enumeration;
6.
7./**





    • filter for enabling IE9 document mode by default









  1. */
    11.public class ResponseHeaderFilter implements Filter {

  2. private FilterConfig filterConfig = null;



  3. public void doFilter(ServletRequest aServletRequest, ServletResponse aServletResponse,
    FilterChain chain)

  4. throws IOException, ServletException {



  5. HttpServletResponse response = (HttpServletResponse) aServletResponse;



  6. // set the provided HTTP response parameters

  7. for (Enumeration e = filterConfig.getInitParameterNames(); e.hasMoreElements();) {

  8. String headerName = (String) e.nextElement();

  9. response.addHeader(headerName, filterConfig.getInitParameter(headerName));

  10. }



  11. // pass the request/response on

  12. chain.doFilter(aServletRequest, response);

  13. }



  14. public void init(FilterConfig aFilterConfig) {

  15. filterConfig = aFilterConfig;

  16. }



  17. public void destroy() {

  18. filterConfig = null;

  19. }
    36.}

Free download pdf