Session timeout processing method of Ajax in Web development
- 2021-07-13 03:44:28
- OfStack
In Java Web development, when session timeout, ordinary page jumps are easy to handle. With regard to the request timeout processing of Ajax, special processing is needed.
First, write a filter or interceptor of System 1 to filter Ajax requests. The following example takes Filter as an example:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest servletRequest=(HttpServletRequest)request;
HttpServletResponse servletResponse=(HttpServletResponse)response;
// Determine whether it is Ajax Request, because Ajax The request appends x-requested-with=XMLHttpRequest
if("XMLHttpRequest".equalsIgnoreCase(servletRequest.getHeader("x-requested-with"))){
servletResponse.addHeader("sessionstatus", "timeout");
}
// Subsequent code omission ......
}
Then, when using Ajax is called on the page, the result is captured for timeout processing, as follows:
// Global ajax Access, process ajax Clear seeking time sesion Timeout
$.ajaxSetup({
type: POST,
contentType:"application/json;charset=utf-8",
// Use complete Capture the result and do timeout processing
complete: function (XMLHttpRequest, textStatus) {
var data = XMLHttpRequest.responseText;
if (data == "timeout") {
if( window.top != window.self ){
window.top.location = "${pageContext.request.contextPath}";
}
}
}
});
According to Header, whether it is an Ajax request is judged, and if it is an Ajax, one status code is thrown out.
This section of processing js code, can be extracted as a method, so that it is convenient to use directly in other places.