Wednesday, November 24, 2010

How to Build a Filter

If you want to add a filter to the webpage, this is a doFilter() function, which would get some information from the request an session, and then, if conditions are satisfied, then it will redirect to another page!


/**
  * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
  */
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  // TODO Auto-generated method stub
  // place your code here
  

  //ServletContext context = config.getServletContext();
  HttpSession session = ((HttpServletRequest)request).getSession();
  ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingCart");
  Statistics stats;
  stats = (Statistics)session.getAttribute("statistic");
  if (stats == null)
  {
   System.out.println("stats is null");
   if (cart != null)
    stats = new Statistics(cart.getSize());
   else
    stats = new Statistics(0);
   session.setAttribute("statistic", stats);
  }
  else if ((stats.getItemsNumber() > 2) && (stats.getTimes() < 5))
  {
   stats.setLastTime(stats.getLastTime()+ 1);
   Random r = new Random();
   int  digit = r.nextInt(4);
   if (((digit % 4) == 0) && (stats.getLastTime() > 4))
   {
    System.out.println("stats is not null");
    HttpServletRequest req = ((HttpServletRequest)request);
    StringBuffer newURL =req.getRequestURL();
    stats.setTimes(stats.getTimes() + 1);
    stats.setItemsNumber(cart.getSize());
    stats.setLastTime(0);
    session.setAttribute("statistic", stats);
    session.setAttribute("address", newURL.toString());
   
    
    RequestDispatcher rd = req.getRequestDispatcher("/add.jspx");
    rd.forward(request, response);
    return;
    
   }
  }
  else
  {
   if (cart != null)
   {
    stats.setItemsNumber(cart.getSize());
    session.setAttribute("statistic", stats);
   }
  }
  
  // pass the request along the filter chain
  chain.doFilter(request, response);
 }

No comments:

Post a Comment