The difference and use of Java Web Filter and Interceptor

Source: Internet
Author: User

the difference and use of Java Web Filter and Interceptor


1, first to clear what is the interceptor, what is the filter    1.1  what is the Interceptor:      Interceptor, in AOP (aspect-oriented  programming) is used to intercept a method or field before it is accessed, and then to add some action before or after it. Interception is an implementation strategy of AOP.      's interpretation of the Chinese document in WebWork is that the interceptor is the object that dynamically intercepts the action call. It provides a mechanism to enable developers to define code that executes before and after an action executes, or to prevent it from executing before an action executes. It also provides a way to extract the reusable parts of an action.       talking about interceptors, there's one more word you should know--the interceptor chain (Interceptor chain, called the Interceptor stack in Struts 2             interceptor stack). The Interceptor chain is a chain that binds the interceptor in a certain order. When accessing an intercepted method or field, interceptors in the interceptor chain are called in the order in which they were previously defined. The implementation principle of the  1.2.     interceptor:   Most of the time, the Interceptor method is invoked by proxy. Struts 2 interceptors are relatively simple to implement. When the request arrives at Struts 2 's servletdispatcher, Struts 2 looks for the configuration file, instantiates the relative interceptor object based on its configuration, and then strings it into a list and then invokes the interceptor in the list one at a time. 1.3  What is a filter filter is a program that runs on the server prior to the servlet or JSP page associated with it. Filters can be attached to one or more servlet or JSP pages, and can be checked for request information that enters these resources. After that, the filter can be chosen as follows: ① calls the resource (that is, invokes the servlet or JSP page) in a regular manner. ② invokes the resource with the modified request information. ③ invokes the resource, but modifies it before sending the response to the client. ④ blocks the resource call and instead goes to another resource, returning aA specific status code or generates a replacement output. The basic principle of the  1.4 servlet filter when used as a filter by the servlet, it can process the client's request. When processing is complete, it is handed over to the next filter, so that the customer's request is processed one by one in the filter chain until the request is sent to the target. For example, a Web site that has submitted a "Modified registration information" page, when the user completed the modification information and submitted, the server in the process of doing two things: to determine whether the client's session is valid, and the data submitted uniformly encoded. These two tasks can be processed in a filter chain consisting of two filters. When the filter is processed successfully, the submitted data is sent to the final target, and if the filter processing is unsuccessful, the view is distributed to the specified error page. The difference between  2, interceptors, and filters  :      1.  interceptors are based on the reflection mechanism of Java, and filters are based on function callbacks. The      2.  interceptor is not dependent on the servlet container, and the filter relies on the servlet container. The       3.  interceptor works only on action requests, while filters can work on almost all requests. The      4.  interceptor can access the action context, the object in the value stack, and the filter cannot be accessed.       5.  The interceptor can be called multiple times during the life cycle of the action, and the filter can only be invoked once when the container is initialized (take struts2 as an example): 1, How to define interceptors in an XML file <interceptors> <interceptor name= "Filteripinterceptor"                            class= "Com.xxxx.web.FilterIPActionInterceptor" &nbsP;/><interceptor-stack name= "Filteripstack" ><interceptor-ref name= "DefaultStack"  / >                               <interceptor-ref name= " Filteripinterceptor " /></interceptor-stack></interceptors> 2, how do you write custom interceptors    public class filteripactioninterceptor extends abstractinterceptor{     /**  Log Control . */    private final log log =  Logfactory.getlog (GetClass ());     /**     *  @see   Com.opensymphony.xwork2.interceptor.abstractinterceptor#intercept (com.opensymphony.xwork2.ActionInvocation)      */     @Override      @SuppressWarnings (" Unchecked ")     pUblic string intercept (actioninvocation invocation)  throws Exception     {        String result = null;         //  gets the current method name.         string  methodname = invocation.getinvocationcontext (). GetName ();         String currIp = null;        try         {             if  (Invocation.getaction ()  instanceof portletaction)              {                 PortletAction action =  (portletaction)  invocation.getaction ();      &nbSp;          currip = action.getrequest (). GETREMOTEADDR ();            }             String ip =  Applicationresource.gethotvalue ("Allow_cache_ip");              if  (Stringutils.isblank (IP)  | |  stringutils.isblank (Currip))             {                 log.error (" The IP allowed to be refreshed does not exist or the IP currently requested is illegal. ");                 throw new  noallowipexception ();            }             else            {                 string[] ips = ip.split (",");                 boolean errorIp = true;                 for  ( String s : ips)                  {                     if  (S.equals (currip))                          errorIp =  false;                }                 //  Judgment ip                 if  (Errorip)                      throw  new noallowipexception ();             }             result = invocation.invoke () ;//Call to intercept method         }         catch  (exception e)         {             log.error ("Exception class name:"  + invocation.getaction (). GetClass ());             log.error ("Exception method:"  +  METHODNAME,&NBSP;E);             throw e;         }         return result;     } }3, how to write filters       1, configure custom interceptors in Web. XML          <filter><filter-name>Redirect Filter</filter-name><filter-class> Com.xx.filter.redirectfilter</filter-class></filter> <filter-mapping><filter-name >redirect filter</filter-name><url-pattern>/xx/xx/*</url-pattern> </ Filter-mapping>     2, how to write a custom interceptor public class redirectfilter  Implements filter {       public void dofilter ( servletrequest request, servletresponse response,               filterChain filterchain)  throws ioexception, servletexception {    //   Get url   long starttime = null;         if  (log.isdebugenabled ())         {             starttime = system.currenttimemillis ();         }               HttpServletRequest httpRequest =  (HttpServletRequest)  request;                            string url = httprequest.getrequesturl (). toString ();                        if (url == null | |  url.trim (). Length ()  == 0)  {                                      return;                                                      }                      if  (Url.indexof (lucenecreatemapping)  != - 1                                   | | &nbSp;url.indexof (lucenesearchmapping)  != -1)  {                                 dofilterforxxx (Request, response, url);                                 } else {                                       doxxxx (request, response,  URL);                                      }         if  (log.isdebugenabled ())          {            long endtime =  System.currenttimemillis ();             thread  currentthread = thread.currentthread ();             string threadname = currentthread.getname ();             log.debug ("["  + threadName +  "]"  +  " <  "                     + this.getclass (). GetName ()  +  " "  + url +  "   "                     +  (ENDTIME&NBsp;- starttime)  +  " ms");        }//  Activates the next filter filterchain.dofilter (request, response);          }}


The difference and use of Java Web Filter and Interceptor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.