想定义拦截器拦截非登陆用户操作,但是我的action分别在不同的package中,那是不是我的拦截器必须要在每个package中都要定义呢? 可不可以定义一个公用的?
1. 首先拦截器的范围是package级别的,正常情况下每个package的interceptors是不一样的,除非继承
那如何为所有的package下的action都定义一个interceptor呢?答案就是继承。
<package name="default" extends="struts-default" namespace="/">
<interceptors>
<interceptor name="custom" class="MyIntercepter"></interceptor>
</interceptors>
</package>
<span style="white-space:pre"> </span><package name="defaultPackage" extends="struts-default">
<interceptors>
<!-- 登录验证 -->
<interceptor name="loginVerify" class="ray.interceptors.LoginInterceptor"></interceptor>
<interceptor-stack name="verifyStack">
<interceptor-ref name="loginVerify"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="verifyStack"></default-interceptor-ref>
<!-- 错误处理Action -->
<global-results>
<result name="error">/WEB-INF/jsp/error.jsp</result>
<result name="login" type="redirect">/index.jsp</result>
</global-results>
</package>
<!-- 所有的action都应该放在对应的package下 -->
<package name="login" extends="defaultPackage" namespace="/">
<!-- struts.xml里action的class应写成spring里对应bean的id -->
<action name="login" class="loginAction" method="login">
<result name="success">/WEB-INF/jsp/manage.jsp</result>
<result name="input" type="redirect">/index.jsp</result>
</action>
</package>
<package name="user" extends="defaultPackage" namespace="/user">
<action name="*_empty" method="{1}" class="ray.action.EmptyAction">
<result name="{1}">/WEB-INF/jsp/user/{1}.jsp</result>
</action>
</package>
2.然后定义一个Interceptor
package ray.interceptors;
import ray.tools.Consts;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
private ActionContext context = null;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
this.context = invocation.getInvocationContext();
Object object = context.getSession().get(Consts.USERSESSION);
if(object == null){
return Action.LOGIN;
} else {
return invocation.invoke();
}
}
}