Struts2 default interceptor and custom interceptor

Source: Internet
Author: User

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.

Implementation Principle

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.

Existing interceptor

Struts 2 provides you with a wide range of interceptor implementations. You can go to the struts2-all-2.0.1.jar or struts2-core-2.0.1.jar package to view the configurations about the default interceptor with the interceptor chain.

The following is what is extracted from the struts-default.xml file:



























Configure and use interceptor

The above interceptor has been configured in the struts-default.xml. If you want to use the interceptor, you only need to "Includes the struts-default.xml file, inherits the struts-default package, and finally uses "Reference interceptor or interceptor stack (interceptor stack ). Once you inherit the struts-default package, all actions call the interceptor stack-defaultStack. Of course, add" "Can overwrite defaultStack.

The following is an example of how to use the interceptor timer. First, create the Action class tuotrial/timerinterceptexception. java with the following content:

Packagetutorial;

Importcom. opensymphony. xwork2.ActionSupport;

Publicclasstimerinterceptexceptionextendsactionsupport {
@ Override
PublicString execute (){
Try {
// Simulate time-consuming operations
Thread. sleep (500 );
} Catch (Exception e ){
E. printStackTrace ();
}
ReturnSUCCESS;
}
}

Configure Action, named Timer. The configuration file is as follows:

"-// Apache Software Foundation // DTD Struts Configuration 2.0 // EN"
Http://struts.apache.org/dtds/struts-2.0.dtd>





/Timer. jsp


As for Timer. jsp, you can write something into it at will. Publish and run the application. In the address bar of the browser, type http: // localhost: 8080/Struts2_Interceptor/Timer. action. After the Timer. jsp page appears, view the server's background output.

2006-12-614: 27: 32com. opensymphony. xwork2.interceptor. TimerInterceptor doLog
Information: Executed action[// Timer! Execute]Took 2859 ms.

Run Timer in your environment! The execution time may vary depending on the performance of your PC. However, the difference between 2859 ms and 500 ms is too far. Why? The reason is that some initial work is required when Timer is loaded for the first time. When you re-request Timer. action, the above output will change:

2006-12-614: 29: 18com. opensymphony. xwork2.interceptor. TimerInterceptor doLog
Information: Executed action[// Timer! Execute]Took 500 ms.

OK. This is the expected result. The above example demonstrates the use of the interceptor timer-used to display the time consumed for executing an action method. This is quite useful when we make a rough performance debugging.

Custom interceptor

As a "framework", scalability is indispensable, because there is nothing in the world that fits the world. Although Struts 2 provides us with such rich interceptor implementations, it does not mean that we lose the ability to create custom interceptors. On the contrary, it is quite easy to define the interceptor in Struts 2.

The reason that the interceptor is stateless is that Struts 2 cannot guarantee to create an instance for each request or action. Therefore, if the interceptor has a status, it will cause concurrency problems.

All the interceptors of Struts 2 directly or indirectly implement the com. opensymphony. xwork2.interceptor. Interceptor interface. In addition, you may prefer to inherit the class com. opensymphony. xwork2.interceptor. AbstractInterceptor.

The following example demonstrates how to implement an authorization interceptor by inheriting AbstractInterceptor.

First, create the authorization interceptor class tutorial. AuthorizationInterceptor. The Code is as follows:

Packagetutorial;

Importjava. util. Map;

Importcom. opensymphony. xwork2.Action;
Importcom. opensymphony. xwork2.ActionInvocation;
Importcom. opensymphony. xwork2.interceptor. AbstractInterceptor;

Publicclassauthorizationinterceptorextends?actinterceptor {

@ Override
PublicString intercept (ActionInvocation ai) throwsException {
Map session = ai. getInvocationContext (). getSession ();
String role = (String) session. get ("ROLE ");
If (null! = Role ){
Object o = ai. getAction ();
If (o instanceofRoleAware ){
RoleAware action = (RoleAware) o;
Action. setRole (role );
}
Returnai. invoke ();
} Else {
ReturnAction. LOGIN;
}
}

}

The above code is quite simple. We can check whether the session has a string with the key "ROLE" to determine whether the user logs in. If the user has logged on, place the role in Action and call Action. Otherwise, the interception directly returns the Action. LOGIN Field. To facilitate role placement in Action, I have defined the interface tutorial. RoleAware. The Code is as follows:

Packagetutorial;

PublicinterfaceRoleAware {
VoidsetRole (String role );
}

Then, create the Action class tutorial. AuthorizatedAccess to simulate access to restricted resources. It is used to obtain the role by implementing RoleAware and display it to ShowUser. jsp. The Code is as follows:

Packagetutorial;

Importcom. opensymphony. xwork2.ActionSupport;

PublicclassAuthorizatedAccessextendsActionSupport implementsRoleAware {
PrivateString role;

PublicvoidsetRole (String role ){
This. role = role;
}

PublicString getRole (){
Returnrole;
}

@ Override
PublicString execute (){
ReturnSUCCESS;
}
}

The following is the code for ShowUser. jsp:

<% @ Page contentType = "text/html; charset = UTF-8" %>
<% @ Taglib prefix = "s" uri = "/struts-tags" %>


Authorizated User


Your role is:

Create tutorial. Roles to initialize the role list. The Code is as follows:

Packagetutorial;

Importjava. util. Hashtable;
Importjava. util. Map;


PublicclassRoles {
PublicMap GetRoles (){
Map Roles = newHashtable (2 );
Roles. put ("EMPLOYEE", "Employee ");
Roles. put ("MANAGER", "Manager ");
Returnroles;
}
}

Next, create Login. jsp to instantiate tutorial. Roles and assign its roles attribute The Code is as follows:

<% @ Page contentType = "text/html; charset = UTF-8" %>
<% @ Taglib prefix = "s" uri = "/struts-tags" %>


Login


Login
Please select a role below:






Create the Action class tutorial. Login to put the role in the session and go to the Action class tutorial. AuthorizatedAccess. The Code is as follows:

Packagetutorial;

Importjava. util. Map;

Importorg. apache. struts2.interceptor. SessionAware;

Importcom. opensymphony. xwork2.ActionSupport;

PublicclassLogin extendsActionSupport implementsSessionAware {
PrivateString role;
PrivateMap session;

PublicString getRole (){
Returnrole;
}

PublicvoidsetRole (String role ){
This. role = role;
}

PublicvoidsetSession (Map session ){
This. session = session;
}

@ Override
PublicString execute (){
Session. put ("ROLE", role );
ReturnSUCCESS;
}
}

Finally, configure the struts. xml file with the following content:

"-// Apache Software Foundation // DTD Struts Configuration 2.0 // EN"
Http://struts.apache.org/dtds/struts-2.0.dtd>








/Timer. jsp


AuthorizatedAccess



/Login. jsp
/ShowRole. jsp


Publish and run the application, and enter http: // localhost: 8080/AuthorizatedAccess. action in the address bar of the browser. At this time, the session does not have a value with the key "ROLE", so the Login. jsp page is returned. After you enter the user name and password, log on to ShowRole. jsp normally and you will see the result to be displayed.



----------------------------

Good stuff comes.

Let's take a test. If you change struts. xml and use the default Interceptor to intercept users during login, what will happen? As follows:

"-// Apache Software Foundation // DTD Struts Configuration 2.0 // EN"
Http://struts.apache.org/dtds/struts-2.0.dtd>








/Timer. jsp


AuthorizatedAccess



/Login. jsp
/ShowRole. jsp



The result is as follows:


Why?

After the interceptor intercepts it, if you do not inject the session (such as implements SessionAware), the session will be lost.

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.