這次帶給大家Ajax+Session失效後即刻跳轉登入頁面,實現Ajax+Session失效後即刻跳轉登入頁面的注意事項有哪些,以下就是實戰案例,一起來看一下。
在Struts應用程式中,我們發出的請求都會經過相應的攔截器進行相關處理,一般都會有一個用戶登入攔截(Session失效攔截);一般請求的話,如果Session失效時,我們會跳到登入頁面,可是如果我們採用AJAX請求時,將會回傳登入頁面的HTML代碼,這肯定不是我們想要的,那我們要如何解決呢?請看以下步驟:
一、建立攔截器
package com.xxx.planeap.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.xxx.common.contants.ConstantsKey; import com.xxx.common.contants.SessionKey; import com.xxx.planeap.domain.User; import com.xxx.planeap.security.SecurityContextUtil; /** * * @author Goma OMA1989@YEAH.NET * @version v1.0 * @since 2012-05-31 * */ public class SecurityInterceptor extends AbstractInterceptor { private static final long serialVersionUID = 1L; private Logger logger = Logger.getLogger(SecurityInterceptor.class); @Override public String intercept(ActionInvocation invocation) throws Exception { // TODO Auto-generated method stub String className = invocation.getAction().getClass().getName(); String action = className.substring(className.lastIndexOf(".")+1,className.length()); String actionName = invocation.getProxy().getActionName(); String result; HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String type = request.getHeader("X-Requested-With"); User user = (User) ActionContext.getContext().getSession().get(SessionKey.CURRENT_USER); if (user == null) { logger.debug("SECURITY CHECKED: NEED TO LOGIN"); if ("XMLHttpRequest".equalsIgnoreCase(type)) {// AJAX REQUEST PROCESS response.setHeader("sessionstatus", ConstantsKey.MSG_TIME_OUT); result = null; } else {// NORMAL REQUEST PROCESS result = ActionSupport.LOGIN; } } else { logger.debug("SECURITY CHECKED: USER HAS LOGINED"); SecurityContextUtil.setCurrentUser(user); boolean hanPerm = SecurityContextUtil.hasPerm(action, actionName); logger.debug("SECURITY CHECKED: PERMISSION---"+action+"."+actionName+"="+hanPerm); result = invocation.invoke(); } return result; } }
二、定義全域AJAX請求結束處理方法
//全局的AJAX访问,处理AJAX清求时SESSION超时 $.ajaxSetup({ contentType:"application/x-www-form-urlencoded;charset=utf-8", complete:function(XMLHttpRequest,textStatus){ //通过XMLHttpRequest取得响应头,sessionstatus var sessionstatus=XMLHttpRequest.getResponseHeader("sessionstatus"); if(sessionstatus=="timeout"){ //这里怎么处理在你,这里跳转的登录页面 window.location.replace(PlanEap.getActionURI("login")); } } });
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
以上是Ajax+Session失效後即刻跳轉登入頁面的詳細內容。更多資訊請關注PHP中文網其他相關文章!