基於Spring JdbcTemplate 的分頁處理 – JAVA編程語言程序開發技術文章

傳統的基於B/S的應用中,Session會話超時後通常是跳轉到應用的首頁,但Ajax請求的處理方式有些不同,下面簡單介紹一下Ajax請求的Session超時處理(超時後返回首頁)
1.首先創建一個Filter
[java] 
import java.io.IOException; 
 
import javax.servlet.Filter; 
import javax.servlet.FilterChain; 
import javax.servlet.FilterConfig; 
import javax.servlet.ServletException; 
import javax.servlet.ServletRequest; 
import javax.servlet.ServletResponse; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
public class AjaxSessionTimeoutFilter implements Filter { 
 
    public void destroy() { 
 
    } 
 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
        HttpServletRequest req = (HttpServletRequest) request; 
        HttpServletResponse res = (HttpServletResponse) response; 
        // 判斷session裡是否有用戶信息 
        if (req.getSession().getAttribute("SPRING_SECURITY_CONTEXT") == null){ 
            // 如果是ajax請求響應頭會有,x-requested-with; 
            if (req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ 
                res.setStatus(911);//表示session timeout 
            }else{ 
                chain.doFilter(req, res); 
            } 
        }else{ 
            chain.doFilter(req, res); 
        } 
    } 
 
    public void init(FilterConfig chain) throws ServletException { 
 
    } 

2.在web.xml中增加以下配置
[html] 
<filter> 
    <filter-name>ajaxSessionTimeout</filter-name> 
    <filter-class>org.tshark.framework.web.filter.AjaxSessionTimeoutFilter</filter-class> 
</filter> 
<filter-mapping> 
    <filter-name>ajaxSessionTimeout</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

3.設置Ajax調用全局參數
[javascript] 
$.ajaxSetup({ 
    contentType : "application/x-www-form-urlencoded;charset=utf-8", 
    complete : function(xhr, textStatus) { 
        $.ts.hideLoading(); 
        //session timeout 
        if (xhr.status == 911) { 
            window.location = rootPath + "/";//返回應用首頁 
            return; 
        } 
    } 
}); 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。