Sunday, January 24, 2016

ServletFilter


Oracle Filters docs

Sequence of invoking filters

Configuring a Chain of Filters

WebLogic Server creates a chain of filters by creating a list of all the filter mappings that match an incoming HTTP request. The ordering of the list is determined by the following sequence:

  1. Filters where the filter-mapping element contains a url-pattern that matches the request are added to the chain in the order they appear in the web.xml deployment descriptor.

  2. Filters where the filter-mapping element contains a servlet-name that matches the request are added to the chain after the filters that match a URL pattern.

  3. The last item in the chain is always the originally requested resource.
In your filter class, use the FilterChain.doFilter() method to invoke the next item in the chain.


Example in web.xml

  <filter-mapping>
   <filter-name>LogFilter</filter-name>
   <servlet-name>*</servlet-name>
  </filter-mapping>
  <filter-mapping>
   <filter-name>ALogFilter</filter-name>
   <servlet-name>*</servlet-name>
  </filter-mapping>
  <filter-mapping>
   <filter-name>BLogFilter</filter-name>
   <servlet-name>*</servlet-name>
  </filter-mapping>

Invoke sequence LogFilter -> ALogFilter -> BLogFilter


Example LogFilter.java

@WebFilter(filterName="LogFilter", urlPatterns="/*")
public class LogFilter implements Filter {
 private FilterConfig filterConfig;
    /**
     * Default constructor. 
     */
    public LogFilter() {
    }
 public void destroy() {
  filterConfig = null;
 }
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  HttpServletRequest httpRequest = (HttpServletRequest)request;
  String uri = httpRequest.getRequestURI();
  String sequence = (String)request.getAttribute("sequence");
  request.setAttribute("sequence", sequence+" LogFilter ");
  if(uri.startsWith(httpRequest.getContextPath()+"/ValidateCode") || uri.startsWith(httpRequest.getContextPath()+"/imgs") || uri.startsWith(httpRequest.getContextPath()+"/LoginView")){
   chain.doFilter(request, response);
  }
  else{
   HttpSession session = httpRequest.getSession();
   User user = (User)session.getAttribute("user");
   if(user!=null) chain.doFilter(request, response);
   else ((HttpServletResponse)response).sendRedirect(httpRequest.getContextPath()+"/LoginView?L");
  }
 }
 public void init(FilterConfig fConfig) throws ServletException {
  this.filterConfig = fConfig;
 }
}

No comments:

Post a Comment