1.拦截器注解
Struts2在com.opensymphony,xwork2.interceptor,annotations 包中定义了3个拦截器注解类型。从而可以直接通过注解的方式,来指定action执行之前和之后需要调用的方法。
Struts2提供的3个拦截器注解类型如下:
action.java
struts.xml
error.jsp
index.jsp 就不说了
Struts2在com.opensymphony,xwork2.interceptor,annotations 包中定义了3个拦截器注解类型。从而可以直接通过注解的方式,来指定action执行之前和之后需要调用的方法。
Struts2提供的3个拦截器注解类型如下:
Before:
标注一个Action方法,该方法在执行Action处理(例如:execute())执行之前调用。如果标注的方法有返回值,并且不为 null 那么这个返回值将作为Action的结果代码。
After:
标注一个Action方法,该方法将Action的处理方法执行之后被调用,如果标注的方法有返回值,那么个返回值将被忽略。
BeforeResult:
标注一个Action方法,该方法将在Action的处理方法执行之后,在result执行之前被调用。如果标注的方法有返回值,那么这个返回值将被忽略。
action.java
package com.sh.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.annotations.After;
import com.opensymphony.xwork2.interceptor.annotations.Before;
import com.opensymphony.xwork2.interceptor.annotations.BeforeResult;
public class AnnotationAction extends ActionSupport {
@Before
public String before(){
System.out.println("执行before方法!");
//如果before 有返回值将作为action的返回结果
return "error";
}
@After
public void after(){
System.out.println("执行after方法!");
}
@BeforeResult
public void beforeResult(){
System.out.println("执行beforeresult方法!");
}
public String execute(){
System.out.println("执行execute方法");
return SUCCESS;
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 如果 注解的action配置改变时候不需要重新启动tomcate --> <constant name="struts.devMode" value="false"/> <constant name="struts.convention.classes.reload" value="true" /> <package name="default" extends="struts-default"> <!-- 使用拦截器注解必须配置 AnnotationWorkflowInterceptor这个拦截器 --> <interceptors> <interceptor name="annotationInterceptor" class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor"/> <interceptor-stack name="annotationStack"> <interceptor-ref name="defaultStack"/> <interceptor-ref name="annotationInterceptor"/> </interceptor-stack> </interceptors> <!-- 然后在使用到了拦截器注解的action中使用上面的 拦截器 --> <action name="annotationAction" class="com.sh.action.AnnotationAction"> <result>/index.jsp</result> <result name="error">/error.jsp</result> <interceptor-ref name="annotationStack"/> </action> </package> </struts>
error.jsp
<body>
before方法 出现异常!
</body>
index.jsp 就不说了