In general, our project has a login filter, the general request is enough to handle. But Ajax is the exception, so the workaround is to set the response to session invalidation.
Altogether divides into the filter and the page JS two parts setting, first looks at the filter the 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 * has session is invalid and user is logged 2 conditions to determine * if it is an AJAX request set session Timeout * @author merlin.ma * */public class Loginfilter
Implements filter{private String RedirectURL = "/login.html";
Private String SessionKey = "UserName"; @Override public void Destroy () {} @Override the public void Dofilter (ServletRequest request, Servletresponse respons E, Filterchain chain) throws IOException, servletexception {httpservletrequest req = (httpservletrequest) reque
St
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 url = filterconfig
. Getinitparameter ("RedirectURL");
String key = Filterconfig.getinitparameter ("SessionKey"); RedirectURL = URL = = null?
Redirecturl:url; SessionKey = key = null?
Sessionkey:key; }
}
Code is simple, not too much to comment on, now look at the JS part of the code. It's based on jquery, of course.
Global AJAX access, processing 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 through 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 starts calling Ajax. In the case of no landing or session failure, you can see the page jump to the login page.