Interceptor problem in Struts2

Source: Internet
Author: User

Most web-side projects will use the "permissions" This thing, first of all to understand that the permissions are tied to the role, that is, the corresponding relationship, permissions: Role =n:1.

Since there is a need for permission, then the interceptor naturally cannot be absent.

1. Interceptor configuration file (Struts.xml):

<package name= "Manage"  namespace= "/"  extends= "default" ><!--Administrator  -->< Interceptors>        <interceptor name= "Admininter"   class= "Cn.yitongworld.util.AdminInteceptor" ></interceptor>         <interceptor-stack name= "Admininterstack" ><interceptor-ref name= "DefaultStack" > </interceptor-ref><interceptor-ref name= "Admininter" ></interceptor-ref></ interceptor-stack> </interceptors><!--  Configure the default interceptor stack--><default-interceptor-ref  Name= "Admininterstack"/> <global-results><result name= "Login"  type= "Chain" > Prelogin</result><result name= "Optresult_success" >/web-inf/manage/operationresult_success.jsp </result><result name= "Optresult_error" >/web-inf/manage/operationresult_error.jsp</result ></global-results><!--  Upload MapSheet  --><action name= "fileUpload"  class= "Cn.yitongworld.action.FileUploadAction" ></ Action></package>

2.java code (Class):

@ParentPackage ("Manage") @Namespace ("/") @Controllerpublic class Manbillaction extends baseaction<bill> {code omitted .........}

3.java Code (Interceptor)

@SuppressWarnings ("Serial") public class admininteceptor extends abstractinterceptor { @Overridepublic  string intercept (actioninvocation invocation) {//Get current user information map<string,  Object> session = actioncontext.getcontext (). getsession ();//The object that gets the current request (as if it were an address) Httpservletrequest request = servletactioncontext.getrequest ();      // Determine if the user exists      if (session.get (const.sess_user)!=null) {     try The  {    //conversion is called the User Object      user user= (users)  session.get ( Const.sess_user)      //Determine if the user is not an administrator      if (user.getId () ==null ||! User.gettype (). Equals (Usertype.adminuser)) {          return  action.login;     }     //determine if the user is Super admin       if (User.getId (). toString (). Equals (Cache.getsetting (Const.superadinid). GetValue ())) {                   //if it is a super administrator, continue to invoke the following action or result             return invocation.invoke ();      }     //determines whether the user's permissions and roles are empty      if ( Mystring.isempty (User.getauthority ()) &&mystring.isempty (User.getrole ())) {      request.setattribute ("Tipmessage", "Sorry, not enough permissions!") ");     return action.error;     }      //gets Url     string url=request.getrequesturi () from the currently requested object;      //intercepts action string action =url.substring (Url.lastindexof ("/") +1) from the URL;  / /Determine if there is permission      if (Hasauth (Invocation, user.getauthority (), &nbsp(action))             //if you have permission to continue the original action .     return invocation.invoke ();      //determine if the role contains permissions       if (! Mystring.isempty (User.getrole ()))              The  //role has multiple permissions              for (String  Role:user.getRole (). Split (",")) {                  //role is actually any permission in the role          if (HasAuth ( Invocation, staticdatacache.getstaticdata (role). GetValue (),  action)                                  //If you have permission to continue with the original action       &. NBsp;return invocation.invoke ();     }      Request.setattribute ("Tipmessage", "Sorry, not enough permissions!") ");      return action.error;}  catch  (exception e)  {e.printstacktrace ();return  "$"; }      }else{     request.setattribute ("Tipmessage", "not logged in, please login first!")      //jumps to The Intercept page      if (!request.getrequesturi (). Contains (" Login "))      session.put (" ReturnUrl ",  getreturnurl (Request));      return action.login;  }}private boolean hasauth (ActionInvocation  Invocation, string authority, string action) {if (! Mystring.isempty (authority)) {for (String auth:authority.split (",")) {if (Mystring.isempty (auth)) {continue;} Try{staticdata sd = staticdatacache.getstaticdata (Auth.trim ()); if (Sd.getvalue () ==null) Continue;if (Sd.getvalue (). Equals (action)) return true;} catch (exception e) {e.printstacktrace (); continue;}}} Return false;} Private string getreturnurl (httpservletrequest request) {map<string, string[]>  Map=request.getparametermap (); Stringbuffer temp=new stringbuffer (Request.getrequesturi () + "?"); Terator<entry<string, string[]>> iter = map.entryset (). Iterator ();while  ( Iter.hasnext ())  {   Map.Entry<String, String[]> entry =  ( map.entry<string, string[]>)  iter.next ();    for (String val:entry.getvalue ( ) {   temp.append (Entry.getkey () + "=" +val+ "&");    }}string value= Temp.tostring (), if (Value.endswith ("&")) {value=value.substring (0, value.length ()-1);} Return temp.tostring ();}}

The program should go this way, and when the user clicks on the URL, it goes directly to the action, but the following 2 annotations appear in action

@ParentPackage ("Manage") @Namespace ("/")

Do you want to ask what this is? After watching the interceptor configuration you will understand, is the corresponding (this interceptor is configured before entering action)

<package name= "Manage" namespace= "/" extends= "Default" >

So when the page data is not loaded, the program sees that the class comments will go to the configuration file to find the corresponding interceptor

<interceptor name= "Admininter" class= "Cn.yitongworld.util.AdminInteceptor" ></interceptor>

According to Interceptor's reference, find the appropriate class to intercept until you meet

return Invocation.invoke ();

How does the program execute when the interception succeeds? And the hardest part for me, the rookie. In general, it is called a method to get a result, the interceptor is not this reason? Of course! The interception was successful! The following "program" can be run only if the interception is successful, and this "program" refers to the class that adds the interceptor annotation. Presumably the program is running like this: 2->1->3->2

Summary: Struts2 Interceptor In fact there are n ways to intercept, I here is the execution of the program before the interception (the user does not have permission to directly do the following action), you can also load the page data after the CRUD interception. It depends on the situation.

Interceptor problem in Struts2

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.