Difference and use of struts2 filter and interceptor, struts2 Filter

Source: Internet
Author: User

Difference and use of struts2 filter and interceptor, struts2 Filter

Java web Filter and interceptor

1.1 What is an interceptor:

Interceptor, 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 policy of AOP.

In the Chinese Document of Webwork, the interceptor is the object for dynamically intercepting Action calls. It provides a mechanism for developers to define the code to be executed before and after an action is executed, or to prevent it from being executed before an action is executed. It also provides a way to extract reusable parts of an action.

When talking about Interceptor, we should also know the Interceptor Chain, which is called the Interceptor Stack in Struts 2 ). The interceptor chain is to link the interceptor into a chain in a certain order. When accessing intercepted methods or fields, the interceptor in the interceptor chain will be called in the order defined previously.

1.2. Implementation principle of interceptor:

 Most of the time, the interceptor method is called by proxy. The interceptor Implementation of Struts 2 is relatively simple. When a request arrives at the ServletDispatcher of Struts 2, Struts 2 searches for the configuration file, instantiates the relative interceptor object based on the configuration, and then Concatenates the object into a list ), finally, the interceptor in the list is called one by one.

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. The filter can be attached to one or more servlet or JSP pages, and the request information for accessing these resources can be checked. After that, the filter can be selected as follows:

① Call resources in a conventional way (that is, call servlet or JSP page ).

② Call resources with modified request information.

③ Call the resource, but modify it before sending a response to the client.

④ Stop this resource call, replace it with another resource, and return a specific status code or generate a replacement output.

 

1.4 basic principles of Servlet Filters

When Servlet is used as a filter, it can process customer requests. After the processing is complete, it will be handed over to the next filter for processing. In this way, the customer's requests are processed one by one in the filter chain until the request is sent to the target. For example, if a website contains a webpage that submits the "modified registration information", after the user completes the modification and submits the information, the server must perform the following two tasks during processing: determine whether the client session is valid. encode the submitted data in a unified manner. These two tasks can be processed in a filter chain composed of two filters. After the filter is processed successfully, the submitted data is sent to the final target. If the filter is not processed successfully, the view is distributed to the specified error page.

 

2. Differences between interceptor and filter:

1. the interceptor is based on the java reflection mechanism, while the 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. the interceptor can only work on action requests, while the filter can work on almost all requests.

4. the interceptor can access objects in the action context and value stack, but the filter cannot.

5. In the lifecycle of an action, the interceptor can be called multiple times, and the filter can only be called once during container initialization.

 

Code Implementation of the Interceptor (taking 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 a custom interceptor?

 

Public class FilterIPActionInterceptor extends actinterceptor {/** 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; // obtain 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 ("the IP address to be refreshed does not exist or the requested IP address is invalid. "); 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 the intercepted 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 a filter?

 

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 /* </url-pattern> </filter-mapping> 2. Compile the custom interceptor public class RedirectFilter implements Filter {public void doFilter (ServletRequest request, servletResponse response, FilterChain filterChain) throws IOExcept Ion, 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 (effececreatemapping )! =-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");} // activate the next Filter filterChain. doFilter (request, response );}}

I personally tested that this procedure is completely correct. If you have different opinions, please leave a message

Source: http://www.ylzx8.cn/web/web/993988.html

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.