1. Interceptor in struts2 (frame function core)
1. Filter VS Interceptor
The filter vs interceptor function is one thing. Filters are technology in the Servlet specification that can filter requests and responses.
Interceptors are technology in the Struts2 framework, implementing the AOP (section-oriented) programming idea, which is pluggable and can be intercepted before or after accessing a certain Action method.
Interceptor Stack: Join the interceptors into a chain in a certain order. When accessing the interceptor method, the interceptors in the Struts2 interceptor chain will be called in sequence in the order they previously defined.
Struts2 execution principle - underlying analysis
2. Custom interceptor
struts2 defines an interceptor interface Interceptor interface.
There are three abstract methods in the Interceptor interface
•init: This method will be called immediately after the interceptor is created, and it will be called only once during the life of the interceptor. The relevant resources can be initialized in this method.
•interecept: This method will be called once every time an action request is intercepted.
•destroy: This method will be called before the interceptor is destroyed, and it will only be called once during the interceptor's life cycle.
Struts will in turn call the intercept method of each interceptor registered by the programmer for an Action. Each time the intercept method is called, Struts will pass an instance of the ActionInvocation interface.
ActionInvocation: Represents the execution status of a given action. The interceptor can obtain the Action object and the Result object associated with the action from the object of this class. After completing the interceptor's own task, the interceptor will call the invoke method of the ActionInvocation object to the next step in the Action processing process.
You can also call the addPreResultListener method of the ActionInvocation object to "hang" one or more PreResultListener listeners. This listener object can do something before starting to execute the action result after the action is executed.
Custom interceptor steps:
a. Write a class to implement the com.opensymphony.xwork2.interceptor.Interceptor interface, or inherit
com.opensymphony.xwork2.interceptor.AbstractInterceptor class. (Adapter mode), generally choose to inherit AbstractInterceptor (interceptor will reside in memory). Because the AbstractInterceptor class implements the Interceptor interface. It provides a blank implementation for init and destroy
Write two interceptors InterceptorDemo1 , and InterceptorDemo2
package com.itheima.interceptor;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class InterceptorDemo1 extends AbstractInterceptor { //This method is called every time the action is accessed public String intercept(ActionInvocation invocation) throws Exception { System.out.println("Before Interceptor"); String rtvalue = invocation.invoke();//Release, why does string return here? Because the final result returns the Result of the Action, and the result of the action is string type System.out.println("Intercept Demo1"); return rtvalue; }}package com.itheima.interceptor;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;import com.opensymphony.xwork2.interceptor.PreResultListener;public class InterceptorDemo2 extends AbstractInterceptor { //This method will be called every time the action is accessed public String intercept(ActionInvocation invocation) throws Exception {// invocation.addPreResultListener(new PreResultListener() {// // public void beforeResult(ActionInvocation invocation, String resultCode) {// System.out.println("Before the result displayed");// }// }); System.out.println("Before the intercept Demo2"); String rtvalue = invocation.invoke();//Release System.out.println("Intercepted Demo2"); return rtvalue; }}b. It needs to be defined in struts.xml, define the interceptor, and define it first before use.
<package name="p1" extends="struts-default"> <!-- Definition interceptor: only valid for the current package --> <interceptor name="interceprotDemo1"></interceptor> <interceptor name="interceprotDemo2"></interceptor> </interceptor> </interceptor>
c. It can be used in action configuration
<action name="action1" method="execute"> <!-- Use the defined interceptor. If no interceptor is specified, all interceptors in the default-stack stack are used by default; 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; }}Running results
Because functions such as file upload, data verification, encapsulating request parameters to action in struts2 are implemented by the interceptor in the default defaultStack of the system, the interceptor we define needs to refer to the default defaultStack of the system, so that the application can use the many functions provided by the struts2 framework.
If no interceptor is specified, all interceptors in the default-stack stack are used by default; once any interceptor is specified, the default is invalid. In addition to using a custom interceptor, you also need to use defaultStack. You can do this
Method 1: (used by yourself), just configure custom and defaultStack in action.
Method 2: (When everyone uses it), if you want all actions under the package to use a custom interceptor, you need to use the interceptor stack interceptor-stack, define an interceptor-stack, and then in the action, you can define the interceptor as the default interceptor through <default-interceptor-ref name="mydefaultStack"/>, and you can get the name of mydefaultStack by yourself.
<interceptors> <interceptor name="interceprotDemo1"></interceptor> <interceptor name="interceprotDemo2"></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" method="login"> <interceptor-ref name="mydefaultStack"></interceptor-ref> <result>/success.jsp</result></action>
3. Struts2's own interceptor
Case 1: Check whether 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 the LoginCheckInterceptor class for login verification
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();//Get the session object through the ServletActionContext object Object user = session.getAttribute("user"); if(user==null){ //No login return "login";//Return to a logical view} return invocation.invoke();//Release}}3. Write configuration file struts.xml
<package name="p2" extends="struts-default"> <interceptors> <interceptor name="loginCheckInterceptor"></interceptor> <interceptor-stack name="mydefaultStack"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="loginCheckInterceptor"></interceptor-ref> </interceptor-ref> </interceptor-stack> </interceptor-stack> </interceptors> <action name="login" method="login"> <result>/login.jsp</result> </action> </package>
4. Write an 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 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)+"nanoseconds"); return rtvalue; }}Write configuration files
<package name="p2" extends="struts-default"> <interceptors> <interceptor name="loginCheckInterceptor"></interceptor> <interceptor name="timerInterceptor"></interceptor> <interceptor-stack name="mydefaultStack"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="loginCheckInterceptor"></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 can be seen from the above, multiple filters can be configured in one action.
4. Custom interceptor: Can specify the method of intercepting or the method of not intercepting
It can specify the method of intercepting or a method without intercepting. When writing a filter, you can implement the MethodFilterInterceptor class, which has two fields. By injecting parameters, you can specify those without intercepting. Only one of the two parameters can be used. When there are fewer intercepts, you can use includeMethods. When there are more intercepts, you can use excludeMethods.
excludeMethods = Collections.emptySet();//Exclude those
includeMethods = Collections.emptySet();//Include those
Case: Continue login verification example.
1. Write a 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.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";//Return to a logical view} return invocation.invoke();//Release}}2. Write configuration files
3. Write an 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("Call add()"Call add()"); return SUCCESS; } public String edit(){ System.out.println("Celling edit service method"); return SUCCESS; } public String login(){ System.out.println("Login"); ServletActionContext.getRequest().getSession().setAttribute("user", "ppp"); return SUCCESS; }} 4. Write a page
addCustomer.jsp
<body> Add a customer</body>
editCustomer.jsp
<body> Modify the 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
<body> oyeah </body>
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.