Java struts learning-interceptor, javastruts
Introduction:
Struts2 interceptor, each interceptor class has only one object instance, that is, the single-instance mode. All the actions that reference this interceptor share the instance of this interceptor class. Therefore, if you use class variables in the interceptor, pay attention to the synchronization problem.
• The interceptor intercepts a method before or after a field.
• Interceptor is an implementation of AOP
• Interceptor Stack)
-The interceptor stack Concatenates 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 implementation principle of the Struts2 interceptor is relatively simple. When requesting the action of struts2, Struts 2 searches for the configuration file, instantiates the corresponding interceptor object according to its configuration, and then concatenates it into a list, finally, the interceptor in the list is called one by one.
Code details
1 // to implement a custom interceptor, you must inherit a MethodFilterceptor class 2 public class LoginInterceptor extends MethodFilterInterceptor {3 private Map <String, Object> session = null; 4 protected String doIntercept (ActionInvocation actionInvocation) throws Exception {5 session = ActionContext. getContext (). getSession (); 6 Object use = session. get ("user"); 7 if (user! = Null) {8 return actionInvocation. invoke (); // allow through 9} else {10 return "login"; 11} 12} 13}
// In struts. use the custom interceptor <interceptors> In the xml configuration file // The Custom interceptor stack <interceptor name = "loginInterceptor" class = "com. nf. action. loginInterceptor "> </interceptor> <interceptor-stack name =" myStack "> <interceptor-ref name =" loginInterceptor "> <param name =" excludeMethods "> loginView, login </param> // excludeMethods indicates that the specified method is excluded. That is, Methods marked as excludeMethods are not blocked, </interceptor-ref> </interceptor-stack> </interceptors> // configure a default interceptor, that is, all actions are blocked, except for param --> <default-interceptor-ref name = "myStack">