1.首先自己定义一个拦截器 Interceptor
package com.itheima.bos.web.interceptor;
import org.apache.struts2.ServletActionContext;
import com.itheima.bos.domain.User;
import com.itheima.bos.utils.BosUtils;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
/*
* 自定义拦截器,实现未登录自动跳转到登陆界面
*/
public class BOSLoginInterceptor extends MethodFilterInterceptor{
//自定义拦截方法
protected String doIntercept(ActionInvocation Invocation) throws Exception {
User user = BosUtils.getLoginUser();
if(user==null)
{
//这个是没有登陆的情况,就是直接跳转到登陆界面
return "login";
}
//如果登录了,就直接放行
return Invocation.invoke();
}
}
2.然后就是在Struts2的配置文件中配置这个拦截器,不然不会起作用的
<interceptors>
<!-- 注册自定义拦截器 -->
<interceptor name="bosLoginInterceptor" class="com.itheima.bos.web.interceptor.BOSLoginInterceptor">
<!-- 指定那些方法不需要拦截 -->
<param name="excludeMethods">login</param>
</interceptor>
<!-- 定义拦截器栈 -->
<interceptor-stack name="myStack">
<interceptor-ref name="bosLoginInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 配置自定义拦截器栈 -->
<default-interceptor-ref name="myStack"/>
<!-- 配置一个全局的结果集 -->
<global-results>
<result name="login">/login.jsp</result>
</global-results>
其中值得注意的就是那个拦截器栈不但需要引入自己的定义的拦截器,还要设置Struts2原带的拦截器栈不然不会起作用。