1. 1 What is an interceptor?
Interceptors are used in AOP (aspect-oriented programming) to intercept a method or field before it is accessed and then add some operations before or after it. Interception is an implementation strategy of AOP.
Chinese documents in Webwork are interpreted as-interceptors are objects that dynamically intercept action calls. It provides a mechanism for developers to define the code to be executed before and after an operation, and to prevent the execution of an operation before it is executed. At the same time, it also provides a method to extract reusable parts from actions.
Speaking of interceptors, there is another word that everyone should know-interceptor chain (called interceptor stack in Struts2). Interceptor chain is to connect interceptors into a chain in a certain order. When accessing an intercepted method or field, the interceptors in the interceptor chain will be called in the previously defined order.
1.2. Implementation principle of interceptor:
Most of the time, the interceptor method is called by the proxy. The interceptor implementation of Struts2 is relatively simple. When the request arrives at the ServletDispatcher of Struts2, Struts 2 will look up the configuration file, instantiate related interceptor objects according to its configuration, then string them into a list, and finally call the interceptors in the list one by one.
1.3 What is a filter?
Filters are programs that run on the server, before servlet or JSP pages. Filters can be attached to one or more servlet or JSP pages, and request information can be checked to enter these resources. After that, the filter can make the following choices:
① Call resources in the normal way (that is, call servlet or JSP pages).
② Use the modified request information to call resources.
③ Call the resource, but modify it before sending the response to the client.
(4) Stop calling resources, switch to other resources, return specific status codes or generate alternative output.
The basic principle of 1.4 Servlet filter
When the Servlet is used as a filter, it can handle the customer's request. After the processing is completed, it will be handed over to the next filter for processing, so that the customer's requests will be processed one by one in the filtering chain until the requests are sent to the target. For example, a website has a page that submits "modify registration information". After the user fills in the modified information and submits it, the server needs to do two tasks when processing it: judging whether the session of the client is valid; Unified coding of submitted data. These two tasks can be handled in a filter chain consisting of two filters. When the filter is successfully processed, the submitted data is sent to the final target; If the filtering process is unsuccessful, the view will be distributed to the specified error page.
2, the difference between interceptor and filter:
1. Interceptor is based on java reflection mechanism, and filter is based on function callback.
2. The interceptor does not depend on the servlet container, and the filter depends on the servlet container.
3. Interceptors can only handle action requests, while filters can handle almost all requests.
4. Interceptors can access objects in the action context and value stack, but filters can't.
5. In the life cycle of the action, the interceptor can be called many times, while the filter can only be called once when the container is initialized.
Code implementation of interceptor (taking struts2 as an example);
1. How to define an interceptor in an xml file
& lt Interceptor & gt
& lt Interceptor name ="filterIPInterceptor "
class = " com . xxxx . web . filteripactioninterceptor "/& gt;
& ltinterceptor-stack name = " filterIPStack " & gt;
& ltinterceptor-ref name = " default stack "/& gt;
& ltinterceptor-ref name = " filterIPInterceptor "/& gt;
& lt/interceptor-stack & gt;
& lt/interceptors & gt;
2. How to stop writing custom interceptors?
The public class FilterIPActionInterceptor extends AbstractInterceptor.
{
/* * Log control. */
Private final log log = logfactory.getlog (getclass ());
/**
* @ see com . open symphony . xwork 2 . interceptor . abstract interceptor # intercept(com . open symphony . xwork 2 . action invocation)
*/
@ Overlay
@SuppressWarnings ("unchecked")
The public string interception (ActionInvocation call) threw an exception.
{
String result = null
//Get the current method name.
string method name = invocation . getinvocationcontext()。 getName();
String currIp = null
attempt
{
If (instanceof invocation. getaction () portlet action)
{
portlet action action =(portlet action)invocation . get action();
currIp = action.getRequest()。 getremote addr();
}
string IP = application resource . get hot value(" ALLOW _ CACHE _ IP ");
if(string utils . is blank(IP)| | string utils . is blank(currIp))
{
Log.error ("The IP allowed to refresh does not exist or the currently requested IP is illegal." );
Throw a new noallowipeexception ();
}
other
{
String[] ips = ip.split(",");
boolean errorIp = true
For (string s: ips)
{
if (s.equals(currIp))
errorIp = false
}
//judging IP
if (errorIp)
Throw a new noallowipeexception ();
}
result = invocation . invoke(); //Call the intercepted method.
}
Capture (exception e)
{
Log.error ("Exception class name:" +invocation.getaction ()). getclass());
Log.error ("exception method:" +methodName, e);
Throw e;
}
Return the result;
}
}
3. How to write a filter
1. Configure a custom interceptor in web.xml
& lt filter & gt
& ltfilter-name & gt; Redirect filter ;
& ltfilter-class & gt; com . xx . filter . redirect filter & lt; /filter-class & gt;
& lt/filter & gt;
& lt filter mapping & gt
& lt/filter-name & gt; redirect filter & lt/filter-name >
& lturl mode & gt/xx/xx/* < /URL-pattern & gt;
& lt/filter-mapping & gt;
2. How to write a custom interceptor?
The public class RedirectFilter implements the filter {
Public Void DoFilter (Servlet Request, ServletResponse,
FilterChain filterChain) raises IOException, ServletException {
//get URL
Long startTime = null
if (log.isDebugEnabled())
{
start time = system . current time millis();
}
Httpservlet request http request = (httpservlet request) request;
string URL = http request . getrequesturl()。 toString();
if (url == null || url.trim()。 length() == 0) {
Return;
}
if(URL . index of(luceneCreateMapping)! = - 1
| | URL . index of(luceneSearchMapping)! = - 1) {
DoFilterForxxx (request, response, URL);
} Otherwise {
Doxxxx (request, response, URL);
}
if (log.isDebugEnabled())
{
long end time = system . current time millis();
thread currentThread = thread . current thread();
string threadName = current thread . getname();
log . debug("["+thread name+"]"+" & lt;
+ this.getClass()。 getName() + " " + url +" "
+(end time-start time)+“ms”);
}
//Activate the next filter.
FilterChain.doFilter (request, response);
}
}