编写拦截器
package com.pb.web.interceptor;
import com.pb.entity.TUser;
import com.pb.utils.BOSUtils;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
/**
* 自定义的拦截器,实现用户未登录自动跳转到登录页面
* @author zhaoqx
*
*/
public class BOSLoginInterceptor extends MethodFilterInterceptor{
//拦截方法
protected String doIntercept(ActionInvocation invocation) throws Exception {
ActionProxy proxy = invocation.getProxy();
String actionName = proxy.getActionName();
String namespace = proxy.getNamespace();
String url = namespace + actionName;
System.out.println(url); ------>命名空间+action名 /userAction_login
//从session中获取用户对象
TUser user = BOSUtils.getLoginUser();
if(user == null){
//没有登录,跳转到登录页面
return "login";
}
//放行
return invocation.invoke();
}
}
工具类
package com.pb.utils;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.pb.entity.TUser;
/**
* BOS项目的工具类
* @author zhaoqx
*
*/
public class BOSUtils {
//获取session对象
public static HttpSession getSession(){
return ServletActionContext.getRequest().getSession();
}
//获取登录用户对象
public static TUser getLoginUser(){
return (TUser) getSession().getAttribute("loginUser");
}
}
在struts.xml中进行配置
<package name="basicstruts2" extends="struts-default">
<interceptors>
<interceptor name="loginInterceptor" class="com.pb.web.interceptor.BOSLoginInterceptor"></interceptor>
<interceptor-stack name="myStack">
<interceptor-ref name="loginInterceptor">
<param name="excludeMethods">login</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"></default-interceptor-ref>
<global-results>
<result name="login">/login.jsp</result>
</global-results>