This article is from: Cao shenghuan blog column. Reprinted please indicate the source:Http://blog.csdn.net/csh624366188
In the previous blog, we read the specific implementation principles of the interceptor and the source code (Discuss the implementation principle and source code analysis of struts2 (8) interceptor), This blog will show you the built-in interceptor of struts2 and how to customize our own Interceptor to achieve the functions we want to implement.
Iv. struts2 built-in interceptor
Struts2 has many built-in interceptors. They provide many core features and optional advanced features of struts2. These built-in interceptors are configured in the struts-default.xml. Only when the interceptor is configured can the interceptor work and run normally. Struts 2 provides you with a wide range of interceptor implementations. You can go to the struts-default.xml in the jar package of struts2 to view the configuration of the default interceptor and interceptor chain. Although built-in interceptors are defined in struts2, they do not all work. Not all interceptors are added to the default interceptor stack. Only the interceptors added to the default interceptor stack take effect. Let's take a look at the interceptors added to the default interceptor Stack:
Next we will learn how to add other interceptors to our application. We will take the timer interceptor as an example. The timer interceptor can count the time when the action is executed. We can modify the default interceptor in the package, so it will replace the defaultstack interceptor stack configured in Struts-default, resulting in struts2 not running properly, for example, unable to get the form value. So how should we configure it correctly? You can add the ultstack interceptor stack based on the new interceptor to ensure the existence of the defastack stack interceptor stack.
<package name="myStruts" extends="struts-default"> <interceptors> <interceptor-stack name="myInterceptor"> ① <interceptor-ref name="timer"/> <interceptor-ref name="defaultStack"/> </interceptor-stack> </interceptors> <default-interceptor-ref name="myInterceptor"/> ② <action name="userAction" class="com.kay.action.UserAction"> <result name="success">suc.jsp</result> <result name="input">index.jsp</result> <result name="error">err.jsp</result> </action></package>
① Add a custom interceptor stack and include the time interceptor and defaultstack interceptor stacks.
② Set the default interceptor stack of the current package to a custom interceptor stack.
Modify the default interceptor of the package to apply all the actions in the package. If you only want to add an interceptor to one of the actions, you can add the default interceptor stack only to the corresponding action:
<Interceptor-ref name = "timer"/>
<Interceptor-ref name = "defaultstack"/>
Note: Do not add <Interceptor-ref name = "defaultstack"/> here. If you forget it, most of struts2 functions cannot be implemented.
5. define your own interceptor
Although struts 2 provides us with such rich interceptor implementations, it cannot meet our needs under certain circumstances. For example, when a user accesses an action, we need to check whether the user has logged on. If the user has not logged on, we will be intercepted before the action is executed. In this case, we need a custom Interceptor. Let's take a look at it, how to implement a custom interceptor.
1. Implement interceptor class
All the interceptors of struts 2 directly or indirectly implement the com. opensymphony. xwork2.interceptor. interceptor interface. This interface provides three
Methods:
1) void Init (); after the interceptor is initialized, the system calls back this method before the interceptor is blocked. For each interceptor, this method is executed only once.
2) void destroy (); this method corresponds to the init () method. The system calls back this method before the interceptor instance is destroyed.
3) string intercept (actioninvocation Invocation) throws exception; this method is the interception action that the user needs to implement. This method returns a string as the logical view.
In addition, the inherited class COM. opensymphony. xwork2.interceptor. abstractinterceptor is a simpler way to implement the interceptor class, because this class provides empty implementations of the init () and destroy () methods, so we only need to implement the intercept method. Another way to implement interceptor is to inherit the methodfilterinterceptor class, which can implement local interception, that is, to specify which method to intercept an action or not to intercept a method.
2. Register a custom interceptor
The custom interceptor class is implemented. Now we need to register this interceptor in struts;
1) register the interceptor and register the interceptor in the package in struts. xml.
<Interceptors> <! -- Name: Interceptor name, class: class of the custom interceptor --> <interceptorname = "Interceptor name" class = "class path of the custom Interceptor"/> </interceptors>
2). Use the interceptor and define the following code in the action that requires the custom Interceptor:
<Action> <Interceptor-refname = "Interceptor name"/> </Action>
Note: many functions of struts2 are implemented based on the Interceptor. If you only use a custom interceptor here, many core functions of struts2 will be lost; therefore, you need to define an interceptor stack (composed of one or more interceptors)
3) interceptor Stack
<Interceptor-stack name = "Interceptor stack name"> <! -- Note that the default interceptor stack of the system should be placed at the front, and a custom interceptor should be added; --> <Interceptor-ref name = "defaultstate"/> <Interceptor-ref name = "Name of the custom Interceptor"/> </Interceptor-stack>
4) use stacks in actions
<Action> <Interceptor-refname = "stack name or interceptor name"/> ..... </Action>
5) if you need to use a custom interceptor for all actions, a default interceptor is defined.
<Default-interceptor-ref name = "permissionstack"/>
NOTE: If another interceptor is used in an action, the default interceptor will be invalid. To ensure that the default interceptor can be used, you need to add other interceptors, you can add other interceptors to the action.
The following describes how to inherit the methodfilterinterceptor class to implement an interceptor for permission control. No other pages are displayed. Here, the configurations of the interceptor class and Struts. XML are displayed:
Interceptor class authorinterceptor:
Package COM. BZU. intecepter; import Java. util. map; import javax. servlet. HTTP. httpservletrequest; import Org. apache. struts2.strutsstatics; import COM. opensymphony. xwork2.actioncontext; import COM. opensymphony. xwork2.actioninvocation; import COM. opensymphony. xwork2.interceptor. methodfilterinterceptor; public class authorinterceptor extends methodfilterinterceptor {@ overrideprotected string dointercept (Action Invocation) throws exception {// todo auto-generated method stubactioncontext context = invocation. getinvocationcontext (); // get httprequesthttpservletrequest request = (httpservletrequest) context through actioncontext. get (strutsstatics. http_request); // you can also use servletactioncontext to obtain httprequest // httpservletrequest request = servletactioncontext. getrequest (); // get the absolute path of the root directory string currenturl = requ EST. getrequesturi (); // captures the relative path of the access. You can use this to compare it with the permission table to control the permission string TargetUrl = currenturl. substring (currenturl. indexof ("/", 1), currenturl. length (); system. out. println (currenturl + ".............. "+ TargetUrl); // obtain the session information through actioncontext, and return map session = context in the form of map. getsession (); // get the username value in the container. If so, the user has logged on and asked him to perform the operation. If not, log on to string username = (string) session. get ("username"); system. out. printl N (username + "username"); If (username! = NULL) {invocation. Invoke ();} return "login ";}}
The following describes the specific struts. xml configuration:
<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype struts public "-// Apache Software Foundation // DTD struts configuration 2.0 // en" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name = "struts. i18n. encoding "value =" UTF-8 "/> <package name =" struts2 "extends =" struts-Default "> <interceptors> <! -- Configure the interceptor that has not been logged on for operation --> <interceptor name = "logininterceptor" class = "com. BZU. intecepter. authorinterceptor "> <Param name =" excludemethods "> login </param> </interceptor> <! -- Re-encapsulate a default interceptor Stack --> <Interceptor-stack name = "mydefaultstack"> <Interceptor-ref name = "logininterceptor"/> <Interceptor-ref name = "defaultstack" /> </Interceptor-stack> </interceptors> <! -- Set the default interceptor stack for this package --> <default-interceptor-ref name = "mydefaultstack"/> <global-Results> <result name = "login">/login. JSP </result> </Global-Results> <action name = "loginaction" class = "com. BZU. action. loginaction "method =" login "> <result name =" success "> success. JSP </result> <result name = "fail"> fail. JSP </result> <result name = "input"> login. JSP </result> </Action> </package> </struts>
The above is a simple permission control code. Specific source code: Click to download
Finally, let's take a look at the differences between the interceptor and the filter:
There are many similarities between the interceptor and the filter, but there are fundamental differences between the two. The main differences are as follows:
1) the interceptor is based on the Java reflection mechanism, and the filter is based on function callback.
2) The filter depends on the servlet container, and the interceptor does not rely on the servlet container.
3) the interceptor can only act on Action requests, while the filter can act on almost all requests.
4) the interceptor can access the 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.