struts2 uses interceptors to implement permission control

 

A custom interceptor can be used in Struts2 to implement login and permission control functions.

 

See the steps below:

1. Custom interceptor class, the class inherits the AbstractInterceptor class 

 

public class AuthorityInterceptor extends AbstractInterceptor {
	
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext ctx = invocation.getInvocationContext();
		User mu = (User) ctx.getSession().get("USER");
                //login control
		if (mu != null && mu.getUserName() != null) {			
		       String actionName = invocation.getInvocationContext().getName();
			//authority control code is written here
			return invocation.invoke();
		} else {
			return "loginError";
		}
	}
}

 2. Write struts.xml

 

<packagename="all" extends="struts-default">

        <!-- Configure the interceptor-->

<interceptors>

<interceptor name="authority" class="com.myinterceptor.AuthorityInterceptor" />

<interceptor-stack name="mydefault">

<interceptor-ref name="defaultStack" />

<interceptor-ref name="authority" />

</interceptor-stack>

</interceptors>

<default-interceptor-ref name="mydefault" />

<!-- <default-action-ref name="loginMasUser" /> -->

 

<!-- Configure the global jump interface-->

<global-results>

<result name="loginError" type="redirect">login.jsp</result>

<result name="error">error.jsp</result>

</global-results>

 

<global-exception-mappings>

<exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>

</global-exception-mappings>

 

      </package>

3. Let the project module implement the interceptor

Other modules create new struts configuration files, and inherit packages configured with interceptors. When accessing the dept module, they will enter the interceptor for interception, for example: struts-dept.xml, 

 

<package name="dept" namespace="/" extends="all">

             <!-- Configure actions to manipulate dept-->

</package>

Other modules can be configured according to the dept module.

In this way, every time the client sends a request to an action, it will be intercepted.

 

Note: login and logout actions should not be configured in the interceptor

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326402571&siteId=291194637