The Interceptor in Struts2 (frame function Core)
1, Filter vs Interceptor
Filter vs Interceptor functionality is one thing. Filters are techniques in the servlet specification that can filter requests and responses.
Interceptors are techniques in the STRUTS2 framework that enable AOP (facet-oriented) programming ideas to be pluggable and can be intercepted before or after access to an Action method.
Interceptor Stack (Interceptor stack): The Interceptor is connected to a chain in a certain order. When accessing the Blocked method, the interceptor in the Struts2 interceptor chain is called sequentially in the order in which it was previously defined
Struts2 execution principle-bottom analysis
2. Custom Interceptor
The STRUTS2 defines an interceptor interface interceptor interface.
There are three abstract methods in the Interceptor interface
Init: This method is called immediately after the Interceptor is created, and it is invoked only once in the life cycle of the interceptor. The necessary initialization of related resources can be made in this method
interecept: Each time an action request is intercepted, the method is invoked once.
Destroy: This method is invoked before the interceptor is destroyed, and it is only invoked once in the life cycle of the interceptor.
Struts invokes the Interecept method of each interceptor that the programmer registers for an Action in turn. Struts passes an instance of the Actioninvocation interface each time the Interecept method is invoked.
Actioninvocation: Represents the execution state of a given action from which the interceptor can obtain the action object and the result object associated with the action. After completing the interceptor's own task, the interceptor calls the Actioninvocation object's Invoke method forward to the next step in the Action process.
You can also call the Addpreresultlistener method of the Actioninvocation object to "hang" one or more Preresultlistener listeners to the Actioninvocation object. The listener object can do something before it starts executing the action result after the action has finished
Custom Interceptor Step:
A, write a class, implement the Com.opensymphony.xwork2.interceptor.Interceptor interface, or inherit
Com.opensymphony.xwork2.interceptor.AbstractInterceptor class. (adapter mode), which generally chooses to inherit Abstractinterceptor (the interceptor resides in memory). Because the Abstractinterceptor class implements the Interceptor interface. And for Init, destroy provides a blank implementation
Write two Interceptor InterceptorDemo1, and InterceptorDemo2
Package com.itheima.interceptor;
Import com.opensymphony.xwork2.ActionInvocation;
Import Com.opensymphony.xwork2.interceptor.AbstractInterceptor; The public class InterceptorDemo1 extends Abstractinterceptor {//action will call the method public String intercept every access (actioninvocation in
Vocation) throws Exception {System.out.println ("before intercepting Demo1");
String rtvalue = Invocation.invoke ();//release, why return string here?
The result of the action returned by the final result is the string type SYSTEM.OUT.PRINTLN ("intercepted after Demo1");
return rtvalue;
}} package Com.itheima.interceptor;
Import com.opensymphony.xwork2.ActionInvocation;
Import Com.opensymphony.xwork2.interceptor.AbstractInterceptor;
Import Com.opensymphony.xwork2.interceptor.PreResultListener; The public class InterceptorDemo2 extends Abstractinterceptor {//action will call the method public String intercept every access (actioninvocation in Vocation) throws Exception {//Invocation.addpreresultlistener (new Preresultlistener () {///public void Beforer Esult (actioninvocation invocation, String ResultcoDE) {//System.out.println ("Before the result is displayed");
System.out.println ("Intercept before Demo2");
String Rtvalue = Invocation.invoke (),//release SYSTEM.OUT.PRINTLN ("after interception Demo2");
return rtvalue;
}
}
b, need to define in the Struts.xml, define interceptor, first define in use.
<package name= "P1" extends= "Struts-default" >
<!--definition Interceptor: Valid only for current package-->
<interceptors>
<interceptor name= "InterceprotDemo1" class= "Com.itheima.interceptor.InterceptorDemo1" ></interceptor>
<interceptor name= "InterceprotDemo2" class= "Com.itheima.interceptor.InterceptorDemo2" ></ interceptor>
</interceptors>
</package>
C, in the action configuration can be used
<action name= "Action1" class= "com.itheima.action.Demo1Action" method= "execute" >
<!--use a defined interceptor. If you have not specified any interceptors, default to use all interceptors in the Default-stack stack;
once any interceptor is specified, the default is invalid
-->
<interceptor-ref name= " InterceprotDemo1 "></interceptor-ref>
<interceptor-ref name=" InterceprotDemo2 "></ interceptor-ref>
<result>/success.jsp</result>
</action>
Implement Action Class Demo1action
Package com.itheima.action;
Import Com.opensymphony.xwork2.ActionSupport;
public class Demo1action extends Actionsupport {
@Override public
String execute () throws Exception {
System . OUT.PRINTLN ("execute executed");
Return SUCCESS
}
}
Run results
Because struts2 such as file upload, data validation, encapsulation request parameters to action and other functions are implemented by the system's default Defaultstack interceptor, so our definition of interceptors need to refer to the system default Defaultstack, This allows applications to use the many features provided by the STRUTS2 framework.
If you have not specified any interceptors, the default is to use all the interceptors in the Default-stack stack; If you specify any interceptor, the default is invalid. Use Defaultstack In addition to using a custom interceptor, you can do so
method One: ( for your own use), simply configure the custom and Defaultstack defaults on the action.
Method Two: (when everyone uses it), if you want all the action under the package to use a custom interceptor, use the interceptor stack interceptor-stack, Define a interceptor-stack, and then in action you can define the interceptor as the default interceptor by <default-interceptor-ref name= "Mydefaultstack"/> Mydefaultstack name can be taken by oneself.
<interceptors>
<interceptor name= "InterceprotDemo1" class= "Com.itheima.interceptor.InterceptorDemo1 "></interceptor>
<interceptor name=" InterceprotDemo2 "class=" Com.itheima.interceptor.InterceptorDemo2 "></interceptor>
<interceptor-stack name=" Mydefaultstack ">
<interceptor-ref name=" Defaultstack "></interceptor-ref>
< Interceptor-ref name= "InterceprotDemo1" ></interceptor-ref>
<interceptor-ref name= " InterceprotDemo2 "></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name= "Action3" class= "com.itheima.action.LoginAction" method= "Login" >
<interceptor-ref name= "Mydefaultstack" ></interceptor-ref>
<result>/success.jsp</result>
</action >
3, Struts2 with the Interceptor
Case 1: Check if the user is logged in
1, write the page login.jsp
<body>
<form action= "${pagecontext.request.contextpath}/login.action" method= "POST" >
< Input type= "text" name= "username"/><br/>
<input type= "text" name= "password"/><br/>
<input type= "Submit" value= "Login"/>
</form>
</body>
2, write login verification of the Interceptor Logincheckinterceptor class
Package com.itheima.interceptor;
Import javax.servlet.http.HttpSession;
Import Org.apache.struts2.ServletActionContext;
Import com.opensymphony.xwork2.ActionInvocation;
Import Com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class Logincheckinterceptor extends Abstractinterceptor {public
String intercept (actioninvocation Invocation) throws Exception {
HttpSession session = Servletactioncontext.getrequest (). getsession ();// Gets the Session object object
user = Session.getattribute ("user") through the Servletactioncontext object;
if (user==null) {
//No login
return "login";//returns to a logical view
} returning
Invocation.invoke ();/Release
}
}
3. Write configuration file Struts.xml
<package name= "P2" extends= "Struts-default" >
<interceptors>
<interceptor name= " Logincheckinterceptor "class=" Com.itheima.interceptor.LoginCheckInterceptor "></interceptor>
< Interceptor-stack name= "Mydefaultstack" >
<interceptor-ref name= "Defaultstack" ></interceptor-ref >
<interceptor-ref name= "Logincheckinterceptor" ></interceptor-ref>
</ interceptor-stack>
</interceptors>
<action name= "Login" class= " Com.itheima.action.CustomerAction "method=" Login ">
<result>/login.jsp</result>
</ Action>
</package>
4, Write action class Customeraction
Package com.itheima.action;
Import Org.apache.struts2.ServletActionContext;
Import Com.opensymphony.xwork2.ActionSupport;
public class Customeraction extends Actionsupport {public
String login () {
System.out.println ("login");
Servletactioncontext.getrequest (). GetSession (). setattribute ("User", "PPP");
Return SUCCESS
}
}
Case 2: monitoring the execution efficiency of action methods
Write Time Monitor filter timerinterceptor
Package com.itheima.interceptor;
Import com.opensymphony.xwork2.ActionInvocation;
Import Com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class Timerinterceptor extends Abstractinterceptor {public
String intercept (actioninvocation invocation) Throws Exception {
long time = System.nanotime ();
String Rtvalue = Invocation.invoke ();
System.out.println (rtvalue+ "Execution Time:" + (System.nanotime ()-time) + nanosecond);
Return Rtvalue
}
}
Writing configuration Files
<package name= "P2" extends= "Struts-default" >
<interceptors>
<interceptor name= " Logincheckinterceptor "class=" Com.itheima.interceptor.LoginCheckInterceptor "></interceptor>
< Interceptor Name= "Timerinterceptor" class= "Com.itheima.interceptor.TimerInterceptor" ></interceptor>
<interceptor-stack name= "Mydefaultstack" >
<interceptor-ref name= "Defaultstack" ></ interceptor-ref>
<interceptor-ref name= "Logincheckinterceptor" ></interceptor-ref>
< Interceptor-ref name= "Timerinterceptor" ></interceptor-ref>
</interceptor-stack>
</ interceptors>
<result name= "Login" >/login.jsp</result>
</action>
</ Package>
As you can see from the above, you can configure multiple filters in an action.
4, Custom Interceptor: can specify the method of interception or do not intercept the method
Can specify the method of interception or do not intercept the method, write a filter, you can implement class Methodfilterinterceptor, which has two fields, by injecting parameters can be specified those do not intercept, two parameters as long as a can, when the interception is less, can use Includemethods, when intercepting more is, can use the method of elimination excludemethods.
Excludemethods = Collections.emptyset ();/excluding those
Includemethods = Collections.emptyset ()//including those
Case: Renew the Login check example.
1. Write Filter Logincheckinterceptor
Package com.itheima.interceptor;
Import javax.servlet.http.HttpSession;
Import Org.apache.struts2.ServletActionContext;
Import com.opensymphony.xwork2.ActionInvocation;
Import Com.opensymphony.xwork2.interceptor.AbstractInterceptor;
Import Com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
public class Logincheckinterceptor extends Methodfilterinterceptor {
protected String dointercept ( Actioninvocation invocation) throws Exception {
HttpSession session = Servletactioncontext.getrequest (). GetSession ();
Object user = Session.getattribute ("user");
if (user==null) {
//No login
return "login";//returns to a logical view
} returning
Invocation.invoke ();/Release
}
}
2, write the configuration file
3, Write action class Customeraction
Package com.itheima.action;
Import Org.apache.struts2.ServletActionContext;
Import Com.opensymphony.xwork2.ActionSupport;
public class Customeraction extends Actionsupport {public
String Add () {
System.out.println ("Invoke Add's service method" );
return SUCCESS;
}
Public String edit () {
System.out.println ("Call Edit service method");
return SUCCESS;
}
Public String Login () {
System.out.println ("login");
Servletactioncontext.getrequest (). GetSession (). setattribute ("User", "PPP");
Return SUCCESS
}
}
4, write the page
addcustomer.jsp
<body>
Add customers
</body>
editcustomer.jsp
<body>
Modify Customer
</body>
login.jsp
<body>
<form action= "${pagecontext.request.contextpath}/login.action" method= "POST" >
< Input type= "text" name= "username"/><br/>
<input type= "text" name= "password"/><br/>
<input type= "Submit" value= "Login"/>
</form>
</body>
success.jsp
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.