Introduction:
Struts2 interceptors, each interceptor class has only one instance of the object, that is, in singleton mode, all actions that refer to this interceptor share an instance of this interceptor class, so if you use class variables in interceptors, be aware of synchronization issues.
• Interceptors are intercepted before or after accessing a method, a field.
• Interceptors are an implementation of AOP
• Interceptor Stack (Interceptor stack)
– The interceptor stack is a chain that binds the interceptor in a certain order.
– When an intercepted method or field is accessed, the interceptor in the interceptor chain is called in the order in which it was previously defined.
• Principle of implementation
The –struts2 interceptor is relatively simple to implement, and when requested by the Struts2 action, Struts 2 looks for the configuration file, instantiates the corresponding interceptor object according to its configuration, and then strings it into a list, the last one to invoke the interceptor in the list.
Code explanation
1 //to implement a custom interceptor you need to inherit a Methodfilterceptor class2 Public classLogininterceptorextendsmethodfilterinterceptor{3 PrivateMap<string,object> session=NULL;4 protectedString dointercept (actioninvocation actioninvocation)throwsexception{5Session =Actioncontext.getcontext (). getsession ();6Object use=session.get ("User");7 if(user!=NULL){8 returnActioninvocation.invoke ();//allowed through9}Else{Ten return"Login"; One } A } -}
// use a custom interceptor in the Struts.xml configuration file <interceptors> // Custom Interceptor Stack class= " Com.nf.action.LoginInterceptor "></interceptor> <interceptor-stack name=" Mystack "> < Interceptor-ref name= "Logininterceptor" > //excludemethods means to exclude the specified method, That is, do not intercept the method labeled Excludemethods, </interceptor-ref> </interceptor-stack></ Interceptors>// Configure a default interceptor, which means that all actions will be intercepted, except param--><default- Interceptor-ref name= "Mystack" >
Java Struts Learning-interceptor