Use struts2 custom interception to implement unified authentication mode

Source: Internet
Author: User

Recently, unified identity authentication is required in project development. the idea of NET is to control through the parent page (base class). If struts2 is used for development, it is convenient to use interceptor and easy to use. Many implementation examples are provided on the Internet, however, they all think that it is a bit difficult for new users to use it. Now I will share my entire implementation method.

First, my project uses spring + struts2 + mybatis and pgsql for the database. Now we need to store user information in the session after the user logs on, in subsequent operations, you need to determine whether the session is invalid in each request. After the session expires, the system prompts that the session has expired and then logs on again.

This is implemented using the Interceptor. First, we create a package for verification, named com. tc. auth, and create the action package and resource file source. struts under the package. The file structure is roughly as shown in

 
 


Next let's write the code for the AuthInterceptor. java file:


[Java]
Package com. tc. auth. action;
 
Import com. opensymphony. xwork2.ActionInvocation;
Import com. opensymphony. xwork2.interceptor. Interceptor;
Import com. tc. blacktea. common. TCSysConst;
Import com. tc. blacktea. util. SessionUtil;
 
Public class AuthInterceptor implements Interceptor {
Private static final long serialVersionUID = 5582842221490358116l;
 
Public void destroy (){
}
 
/**
* Run
*/
Public void init (){
}
 
Public String intercept (ActionInvocation actionInvocation) throws Exception {
System. out. println ("<user authentication detection interceptor initialization ...");
// SessionUser if the session does not exist, the user returns the index view.
If (SessionUtil. GetSession ("USER_SESSION_KEY") = null) {// here I used the session encapsulation class I wrote.
Return "autherror ";
}
String result = actionInvocation. invoke (); // here, the original request invoke is continued and no other operations are performed.
Return result;
}
}
Package com. tc. auth. action;

Import com. opensymphony. xwork2.ActionInvocation;
Import com. opensymphony. xwork2.interceptor. Interceptor;
Import com. tc. blacktea. common. TCSysConst;
Import com. tc. blacktea. util. SessionUtil;

Public class AuthInterceptor implements Interceptor {
Private static final long serialVersionUID = 5582842221490358116l;

Public void destroy (){
}

/**
* Run
*/
Public void init (){
}

Public String intercept (ActionInvocation actionInvocation) throws Exception {
System. out. println ("<user authentication detection interceptor initialization ...");
// SessionUser if the session does not exist, the user returns the index view.
If (SessionUtil. GetSession ("USER_SESSION_KEY") = null) {// here I used the session encapsulation class I wrote.
Return "autherror ";
}
String result = actionInvocation. invoke (); // here, the original request invoke is continued and no other operations are performed.
Return result;
}
}

 

Next, let's look at how the interceptor configuration is written:


[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.1 // EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<Struts>
<! -- Default (global) package configuration -->
<Package name = "userAuth" extends = "struts-default" <strong> <span style = "color: # ff0000; "> namespace ="/"</span> </strong>
<Interceptors>
<Interceptor name = "AuthInterceptor"
Class = "<strong> <span style =" color: # 3333ff; "> com. tc. auth. action. AuthInterceptor </span> </strong>">
</Interceptor>
<! -- The default value must be placed at the bottom! -->
<Interceptor-stack name = "userAuthStack">
<Interceptor-ref name = "AuthInterceptor"> </interceptor-ref>
<Strong> <span style = "color: # ff0000;"> <interceptor-ref name = "defaultStack"> </interceptor-ref> </span> </strong>
</Interceptor-stack>
</Interceptors>
<! -- Default Interceptor. All actions in this package will be intercepted. If ACTION defines the interceptor again, it will be invalid -->
<Strong> default-interceptor-ref </strong> name = "userAuthStack"> </default-interceptor-ref>
<Global-results>
<! -- Homepage -->
<Result name = "index">/jsp/index. jsp </result>
<Result name = "adminLoginPage">/jsp/index. jsp </result>
<Result name = "autherror">/jsp/Error. jsp </result>
</Global-results>
<! -- Log out. -->
<! -- <Action name = "existLogin _ *" class = "existLoginAction" method = "{1}">
<Result name = "index">/jsp/Error. jsp </result> </action> -->
</Package>
</Struts>
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.1 // EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<Struts>
<! -- Default (global) package configuration -->
<Package name = "userAuth" extends = "struts-default" <strong> <span style = "color: # ff0000; "> namespace ="/"</span> </strong>
<Interceptors>
<Interceptor name = "AuthInterceptor"
Class = "<strong> <span style =" color: # 3333ff; "> com. tc. auth. action. AuthInterceptor </span> </strong>">
</Interceptor>
<! -- The default value must be placed at the bottom! -->
<Interceptor-stack name = "userAuthStack">
<Interceptor-ref name = "AuthInterceptor"> </interceptor-ref>
<Strong> <span style = "color: # ff0000;"> <interceptor-ref name = "defaultStack"> </interceptor-ref> </span> </strong>
</Interceptor-stack>
</Interceptors>
<! -- Default Interceptor. All actions in this package will be intercepted. If ACTION defines the interceptor again, it will be invalid -->
<Strong> default-interceptor-ref </strong> name = "userAuthStack"> </default-interceptor-ref>
<Global-results>
<! -- Homepage -->
<Result name = "index">/jsp/index. jsp </result>
<Result name = "adminLoginPage">/jsp/index. jsp </result>
<Result name = "autherror">/jsp/Error. jsp </result>
</Global-results>
<! -- Log out. -->
<! -- <Action name = "existLogin _ *" class = "existLoginAction" method = "{1}">
<Result name = "index">/jsp/Error. jsp </result> </action> -->
</Package>
</Struts> note the following points for the above code:

1. If the namespace of the package is "/", it indicates that it is a global Interceptor. You can call it anywhere in the struts configuration file.

2. The class attribute of interceptors/interceptor is the class access path of the action just written above.

3. The default interceptor defaultStack of interceptors/interceptor-stack must be written at the end; otherwise, it will become invalid.

4. default-interceptor-ref is the name of the interceptor that defines all actions. By default, the interceptor with the name attribute is executed before the request context is executed.

For more information, see:

 


After all the interceptors are defined, we will use them next,

First, we write the following xml configuration information in the struts-user.xml file under the user package:


[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.1 // EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<Struts>
<Package name = "struts-user" extends = "<strong> <span style =" color: # ff0000; "> userAuth </span> </strong>" namespace = "/user">

<! -- Define Action (login. action) -->
<Action name = "userManage" class = "com. tc. user. action. UserAction">
<Strong> <span style = "color: # ff0000;"> <interceptor-ref name = "userAuthStack"/> </span> </strong>
<! -- Define the string name corresponding to the forwarding path -->
<Result name = "error">/jsp/Error. jsp </result>
<Result name = "success">/jsp/user/userlist. jsp </result>
<Result name = "userinfo">/jsp/user/userinfo. jsp </result>
</Action>
</Package>
</Struts>
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.1 // EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<Struts>
<Package name = "struts-user" extends = "<strong> <span style =" color: # ff0000; "> userAuth </span> </strong>" namespace = "/user">
 
<! -- Define Action (login. action) -->
<Action name = "userManage" class = "com. tc. user. action. UserAction">
<Strong> <span style = "color: # ff0000;"> <interceptor-ref name = "userAuthStack"/> </span> </strong>
<! -- Define the string name corresponding to the forwarding path -->
<Result name = "error">/jsp/Error. jsp </result>
<Result name = "success">/jsp/user/userlist. jsp </result>
<Result name = "userinfo">/jsp/user/userinfo. jsp </result>
</Action>
</Package>
</Struts> 1. Note that the extends attribute of the package must inherit the package name of the custom interceptor.

2. Add the interceptor-ref node to our action. Specify the interceptor name in the name attribute.

After the configuration is complete, we can perform the above configuration in any action that requires authentication to verify and filter information. As long as these similar principles are used, we can perform such operations as identity verification, data filtering, access statistics, and page PR to achieve the effect, don't talk about it anymore. Try it now!

Author: qq%7%94
 


 

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.