import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
public class ExampleInterceptor extends MethodFilterInterceptor {
//重写方法拦截器拦截方法
@Override
protected String doIntercept(ActionInvocation arg0) throws Exception {
System.out.println("start invoking3...");
String result = arg0.invoke();
System.out.println("end invoking3...");
return result;
}
LoginAction中增加了method方法
public String method()throws Exception {
FORWARD = "success";
return FORWARD;
}
<struts> <!-- Action所在包定义 --> <package name="C04.3" extends="struts-default"> <!-- 拦截器配置定义 --> <interceptors> <interceptor name="example" class="com.example.struts.interceptor.ExampleInterceptor"> </interceptor> </interceptors> <!-- 缺省拦截器栈配置定义 <default-interceptor-ref name="example"></default-interceptor-ref> --> <!-- Action名字,类以及导航页面定义 --> <!-- 通过Action类处理才导航的的Action定义 --> <action name="Login" class="com.example.struts.action.LoginAction" method="method"> <result name="input">/jsp/login.jsp</result> <result name="success">/jsp/success.jsp</result> <!-- Action方法拦截器配置定义 --> <interceptor-ref name="example"> <!-- 被拦截方法配置定义 --> <param name="includeMethods">method</param> <!-- 不被拦截方法配置定义 --> <param name="excludeMethods">method,execute</param> </interceptor-ref> </action> </package> </struts>
LoginAction.java中又定义了一个名为“method”方法,在struts.xml配置文件中,因为LoginAction中有execute方法,又有method方法,因此在<Action>中,请读者注意struts.xml中黑体部分,该部分代码表示现在LoginAction只执行method方法,而execute方法不被执行。笔者在<Action>中增加了一个“method”属性,该属性中“=”后面的内容是Action中具体方法名,如果不写“method”属性,Action是缺省执行execute方法。如果写了“method”属性,Action就执行“=”后写的具体方法。而不会执行execute方法。“example”拦截器还是如之前在<Action>前定义。在<Action>中配置“example”拦截器,笔者增加了“includeMethods”和“excludeMethods”两个param属性定义。“includeMethods”表示的是被拦截器拦截的方法。方法名写在<param>和</param>之间,如果有多个方法开发人员需要拦截器拦截,则方法名之间以“,”相隔。“excludeMethods”表示的是不被拦截器拦截的方法。如果有多个方法,也是以“,”相隔
struts.xml配置文件中要么没有<default-interceptor-ref >定义,如果定义了也只能定义一次。该标签在struts.xml配置文件中只能写在<Action>前,而且只能写一次。不能重复定义它
本文介绍Struts框架中拦截器的配置与使用方法。详细解释如何定义自定义拦截器并将其应用于特定Action方法,包括如何指定被拦截与未被拦截的方法。通过实例展示如何在struts.xml中进行配置。
231

被折叠的 条评论
为什么被折叠?



