Ajax通讯时,检查Session是否过期

前端之家收集整理的这篇文章主要介绍了Ajax通讯时,检查Session是否过期前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
场景:ajax通讯模式下,客户端校验Session是否过期。

实现:这里用到一个拦截器,检查Session中的用户是否存在

public class LoginFilter extends AbstractInterceptor{

	private static final long serialVersionUID = 1L;
	
	private Logger logger =Logger.getLogger(LoginFilter.class.getName());
	
	private static String Error = "errorLogin";
	private String msg ;

	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		
		logger.debug("...LoginFilter开始载拦...");
		
		//取得请求的action实例
		ActionContext ctx = arg0.getInvocationContext();
		//取得提交URI
		HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);
		String actionName = ctx.getContext().getName();
		if("goAIOPortal".equals(actionName)||"goRealware".equals(actionName)||"loginCheck".equals(actionName)||"loginCh".equals(actionName)||"ukeyloginCheck".equals(actionName)||"loginCheckPass".equals(actionName)) {
			return arg0.invoke();
		}

		//获取session
		logger.debug("...LoginFilter:判断用户登录...");
		Map<String,Object> session =ctx.getSession();
		
		//异步传输
		if (request.getHeader("x-requested-with") != null && 
				request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {  
			if (session.get("user") == null) 
			{
				//if(!autoLogin(session,request)){
					msg = "用户登录登录超时,请重新登录!";
					logger.debug("用户登录,重新登录!");
					//request.setAttribute("msg",msg);
					response.setContentType("text/json;charset=UTF-8");
					response.setHeader("Cache-Control","no-cache");
					PrintWriter pw = null;
					try {
						pw = response.getWriter();
						pw.write("overdue");
					} catch (IOException e) {
						throw new EVoucherException("获取http写入流异常" + e.getMessage());
					} finally {
						if (pw != null) {
							pw.close();
						}
					}

					return null;
				//}
			}else{

				return arg0.invoke();
			}
			
		//同步传输
		}else{
			if (session.get("user") == null) 
			{
				logger.debug("用户登录,重新登录!");	
				return Action.LOGIN;
				
			}else{
				return arg0.invoke();
			}
		}
		
		
	}
	
	//自动登陆
	private boolean autoLogin(Map<String,Object> session,HttpServletRequest request){
		return false;
	}

}


然后在检测的时候判断执行以下方法就行了。

/**
 * ajax通讯模式下,客户端校验Session是否过期。
 * @param msg
 */
function checkSessionOverdue(msg){
	if (msg == 'overdue'){
		alert("登录时间过长,将重新登录!!")
		window.top.location.href = '/realware/jsp/common/Login.jsp';
	}
	
}

猜你在找的Ajax相关文章