Using technology: HTML + Servlet + Filter + jQuery
In general, our project has a login filter, which is usually sufficient to handle the request. But Ajax is the exception, so the workaround is to set the response to invalid session.
Altogether divided into the filter and the page JS two parts of the settings, first look at the filter modification:
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;import javax.servlet.http.httpsession;/** * Login Filter * Whether the session is invalid and whether the user is logged in 2 conditions of judgment
* Set Session Timeout If it is an AJAX request * @author Merlin.ma * */public class Loginfilter implements filter{private String Redire Cturl = "/login.html"; Private String SessionKey = "UserName"; @Override public void Destroy () {} @Override public void DoFilter (ServletRequest request, Servletresponse Res Ponse, Filterchain chain) throws IOException, servletexception {httpservletrequest req = (HttpS ervletrequest) Request; HttpServletResponse rep = (HttpServletResponse) response; HttpSession session = Req.getsession (); if (session = = NULL | | Session.getattribute (sessionkey) = = null) {//If the judgment is an AJAX request, set directly to the session timeout if ( Req.getheader ("x-requested-with") = null && req.getheader ("X-requested-with"). Equals ("XMLHttpRequest")) { Rep.setheader ("Sessionstatus", "timeout"); } else {Rep.sendredirect (Req.getcontextpath () + redIrecturl); }}else {Chain.dofilter (request, response); }} @Override public void init (Filterconfig filterconfig) throws servletexception {String u RL = Filterconfig.getinitparameter ("RedirectURL"); String key = Filterconfig.getinitparameter ("SessionKey"); RedirectURL = URL = = null? Redirecturl:url; SessionKey = key = = null? Sessionkey:key; } }
The code is simple, do not comment too much, now look at the JS section of the code. Of course it's jquery-based ~ ~
Global AJAX access, handling Ajax sesion timeout $.ajaxsetup ({ contentType: "Application/x-www-form-urlencoded;charset=utf-8", complete:function (XMLHttpRequest, textstatus) { var sessionstatus = Xmlhttprequest.getresponseheader (" Sessionstatus "); Get the response header via XMLHttpRequest, Sessionstatus, if (sessionstatus = = "Timeout") { //If the timeout is processed, specify the page to jump to Window.location.replace ("login.html");}} );
The page loads the JS code and then starts calling Ajax. If you do not log in or the session fails, you can see the page jump to the login page.
Ajax requests encounter a solution with no login and session failure