The difference and use of Java Web Filter and Interceptor

Source: Internet
Author: User
Tags aop log log java web

1, first to identify what is the interceptor, what is the filter
1.1 What is an interceptor:
Interceptors, which are used in AOP (aspect-oriented programming) to intercept a method or field before it is accessed, and then add some action before or after it. Interception is an implementation strategy of AOP.
The Chinese document in WebWork is interpreted as--interceptors are objects that dynamically intercept action calls. 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.
When it comes to interceptors, there's one more word you should know-the interceptor chain (Interceptor Chain, called the Interceptor stack interceptor stack in struts 2). 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.
1.2. How to implement the Interceptor:
Most of the time, the Interceptor method is invoked in the form of proxies. The block implementation of Struts 2 is relatively straightforward. When the request arrives at the servletdispatcher of Struts 2, struts 2 looks for the configuration file, instantiates the relative interceptor object based on its configuration, and then strings it into a list, the last one to invoke the interceptor in the list.
1.3 What is a filter
A 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 this, the filter can be selected as follows:
① calls the resource (that is, 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, returns a specific status code, or generates a replacement output.

Fundamentals of the 1.4 servlet filter
When the servlet is used as a filter, 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.

2, the difference between the interceptor and the filter:
1. Interceptors are based on the reflection mechanism of Java, and filters are based on function callbacks.
2. Interceptors are not dependent on the servlet container, and the filter relies on the servlet container.
3. Interceptors only work on action requests, while filters can work on almost all requests.
4. The 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 called once when the container is initialized

The code implementation of the Interceptor (take struts2 as an example):
1. How to define an interceptor in an XML file
<interceptors>
<interceptor name= "Filteripinterceptor"
class= "Com.xxxx.web.FilterIPActionInterceptor"/>
<interceptor-stack name= "Filteripstack" >
<interceptor-ref name= "Defaultstack"/>

<interceptor-ref name= "Filteripinterceptor"/>
</interceptor-stack>
</interceptors>

2. How to 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 ();
Currip = Action.getrequest (). GETREMOTEADDR ();
}
String IP = applicationresource.gethotvalue ("Allow_cache_ip");

if (Stringutils.isblank (IP) | | Stringutils.isblank (Currip))
{
Log.error ("Allow the refreshed IP to not exist or the currently requested IP is illegal.");
throw new Noallowipexception ();
}
Else
{
string[] ips = Ip.split (",");
Boolean Errorip = true;
for (String s:ips)
{
if (S.equals (Currip))
Errorip = false;
}
Judge 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, E);
Throw e;
}

return result;
}

}

3. How to Write Filters

1. Configure a custom interceptor 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
|| 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-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.