欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Struts2拦截器控制session失效

程序员文章站 2022-05-28 23:45:58
...

com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.huangt.bean.SystemUser;
/* session过期、登录有效性及操作的权限验证拦截器 */
@SuppressWarnings("serial")
public class LoginedCheckInterceptor extends AbstractInterceptor {
/** 拦截请求并进行登录有效性验证 */
public String intercept(ActionInvocation ai) throws Exception {
HttpServletRequest request = (HttpServletRequest)ai.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
//取得请求的URL
String url = ServletActionContext.getRequest().getRequestURL().toString();
HttpServletResponse response = ServletActionContext.getResponse();
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires",0);
//对登录与注销请求直接放行,不予拦截
if (url.indexOf("login.action")!=-1 || url.indexOf("logout.action")!=-1){
return ai.invoke();
}
else{
//验证Session是否过期
if(!ServletActionContext.getRequest().isRequestedSessionIdValid()){
//session过期,转向session过期提示页,最终跳转至登录页面
return "tologin";
}
else{
HttpSession session = request.getSession();
String userId = (String)session.getAttribute(SessionConstant.SESSION_USER)
//验证是否已经登录
if (userId == null){
//尚未登录,跳转至登录页面
return "tologin";
}else{
return ai.invoke();

}
}
}
}
}