拦截器代码片段:
public String intercept(ActionInvocation ai) throws Exception{
Object object = ai.getAction();
if (object != null && object instanceof LoginAction) {
LoginAction loginaction = (LoginAction) object;
//取得姓名
String username = loginaction.getUsername();
if("DLuffy".equals(username)){
ActionContext ac = ai.getInvocationContext();
ac.put("exist", "此账号已经被注册");
return Action.LOGIN;
}else{
return ai.invoke();
}
}
return null;
}
如果struts配置文件里默认拦截器defaultStack在自定义拦截器loginInterceptor的后面,如下
<action name="loginAction" class="com.demo1.action.LoginAction" method="checkLogin">
<result name="success">/index.jsp</result>
<result name="login">/login.jsp</result>
<interceptor-ref name="loginInterceptor"/><!--自定义拦截器-->
<interceptor-ref name="defaultStack"/><!--默认拦截器-->
</action>
则自定义拦截器里取得姓名username为null。这是因为默认拦截器将自定义拦截器覆盖。
正确配置应为默认拦截器defaultStack在自定义拦截器loginInterceptor的前面,如下图
<action name="loginAction" class="com.demo1.action.LoginAction" method="checkLogin">
<result name="success">/index.jsp</result>
<result name="login">/login.jsp</result>
<interceptor-ref name="defaultStack"/><!--默认拦截器-->
<interceptor-ref name="loginInterceptor"/><!--自定义拦截器--></span>
</action>
此时因为defaultStack中拦截器params可以解析客户端请求参数。<interceptor name="params">
<param name="excludeParams">dojo\..*</param>
</interceptor>
所以<interceptor-ref name="defaultStack"/>还可替换成<interceptor-ref name="params"/>
一个action配置了自定义拦截器,如果不显示配置默认拦截器,默认拦截器就不会再起作用。若想继续使用defaultStack就需手动引入。