Custom interceptor of Struts2
Login. jsp
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% request. getSession (). setAttribute ("user", "has logined"); %> the user has logged on!
To customize the Interceptor, you must implement the com. opensymphony. xwork2.interceptor. Interceptor interface.
Package struts2.example. interceptor; import com. opensymphony. xwork2.ActionContext; import com. opensymphony. xwork2.ActionInvocation; import com. opensymphony. xwork2.interceptor. interceptor; public class PermissionInterceptor implements Interceptor {// This method is executed when the class is destroyed @ Overridepublic void destroy () {// TODO Auto-generated method stub} // the interceptor will be instantiated at struts2 startup @ Overridepublic void init () {// TODO Auto-generate D method stub} // when the action is intercepted, the method @ Overridepublic String intercept (ActionInvocation invocation) throws Exception {// first checks whether the user has logged on to the Object user = ActionContext. getContext (). getSession (). get ("user"); if (user! = Null) {// user is not empty, indicating that the user has logged on to return invocation. invoke (); // call the method intercepted by this method to execute} ActionContext. getContext (). put ("message", "You are not authorized to perform this operation"); return "success ";}}
Login result page showInfo. jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
$ {Message}
/WEB-INF/page/showInfo.jsp
After a custom interceptor is registered in the action, many default interceptors of struts2 will be blocked and many default functions of struts2 will not be available. To solve this problem, you can define the interceptor stack. In the interceptor stack, it is defined to be executed first, and then after defined.
If you want to allow all actions in the package to use this interceptor
If you want an interceptor to be specific to an action and do not want the action to lose some of struts2's default interception functions, you can define multiple interceptors under this action.
You can view the specific information of defaultStack in the struts-default.xml:
dojo\..*,^struts\..*
input,back,cancel,browse
input,back,cancel,browse