Home > Java > javaTutorial > body text

Solving the problem of session timeout in Javaweb project

黄舟
Release: 2017-09-21 10:16:04
Original
2334 people have browsed it

This article mainly introduces the session timeout solution for Javaweb projects. The classification of the solution is relatively clear and the content is detailed. Friends in need can refer to it.

In Java Web development, Session provides us with a lot of convenience. Session is maintained between the browser and the server. Session timeout is understood as: a Session is created between the browser and the server. Since the client does not interact with the server for a long time (sleep time), the server destroys this Session. When the client interacts with the server again, the previous Session does not exist. .

0. Requirements

Need to log in to intercept all /web/** requests, and jump to the login page when the Session times out.

1. Introduction

Generally speaking, the Session timeout will be configured during project use. If not configured, the default value is 30 Minutes, that is, after the user does not operate for 30 minutes, the Session will become invalid and the user will need to log in to the system again.

Session timeout configuration is configured in the web.xml of the main project, as follows:


<span style="font-size: 14px;"> <!-- 设置Session超时时间 -->  
    <session-config>  
        <!-- 分钟 -->  
            <session-timeout>60</session-timeout>  
            <!-- 去除URL上显示的jsessionid, 防止打开Tab页时出现JS错误 -->  
            <tracking-mode>COOKIE</tracking-mode>  
    </session-config></span><span style="font-size:24px;">  
</span>
Copy after login

2. Requested Classification

Requests in current projects are mainly divided into two types: one is a normal request, which initiates a request to return views and models; the other is an Ajax request, which mainly returns model data. When the backend performs processing, it must return different content according to different requests.

For ordinary requests, we directly return the JavaScript script. The content of the script can be to jump to the login page.

For Ajax requests, a status code other than 200 needs to be returned, so that the ajax request will enter the error callback function and the global Ajax error callback function AjaxError.

3. Backend processing Session timeout

The backend uses SpringMVC’s interceptor processing. Why is an interceptor used here? On the one hand, the request URL cannot be too restrictive, such as /*. It is a waste of resources to filter all requests. On the other hand, some URLs do not need to be intercepted. For example, requests to the login page must not be intercepted, otherwise they will be redirected in a loop. On the other hand, we only need to intercept controller requests and not other requests.

Let’s take a look at the implementation of the interceptor:


/** 
* Web端登录拦截器
* 处理请求时Session失效的问题,包含Ajax请求和普通请求
* @ClassName WebLoginInterceptor 
* @author zhangshun
* @date 2016年10月20日 上午11:14:52
*/
public class WebLoginInterceptor extends HandlerInterceptorAdapter{
    /**
     * 日志对象
     */
    private Logger logger = LoggerFactory.getLogger(WebLoginInterceptor.class);
    /**
     * 默认注销URL
     * 即Session超时后,发起请求到此地址,只对普通请求有效
     */
    private static final String DEFAULT_LOGOUT_URL = "/web/logout";
    /**
     * 注销URL
     */
    private String logoutUrl;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        User user = SessionUtils.getUserFromRequestAcrossCas(request);
        String uri = request.getRequestURI();    
                if(user == null){
                    response.setContentType("text/html;charset=UTF-8");
                    if(request.getHeader("x-requested-with") != null 
                                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ 
                        // Ajax请求, 前段根据此header进行处理
                        response.setHeader("sessionTimeout", "Session time out, you need relogin !");
                        // 返回未认证的状态码(401)
                        response.setStatus(HttpStatus.UNAUTHORIZED.value());
                            logger.debug("请求路径:" + uri + ", 请求方式 :Ajax请求, Session超时, 需要重新登录!");
                        }else{
                            // 普通请求
                            String path = request.getContextPath();
                            StringBuffer basePath = new StringBuffer()
                                    .append(request.getScheme())
                                    .append("://")
                                    .append(request.getServerName())
                                    .append(":")
                                    .append(request.getServerPort())
                                    .append(path)
                                    .append("/");
                            StringBuffer responseStr = new StringBuffer()
                                    .append("<html><header><script type=\"text/javascript\">")
                                    .append("window.location.href=\"")
                                        .append(basePath).append(getLogoutUrl()).append("\";")
                                    .append("</script></header></html>");
                                response.getWriter().write(responseStr.toString());
                                logger.debug("请求路径:" + uri + ",请求方式 :普通请求, Session超时, 需要重新登录!");
                        }
                    return false;
                }
                return true;
    }
    public String getLogoutUrl() {
        // 使用默认值
        if(StringUtils.isEmpty(logoutUrl)){
            return DEFAULT_LOGOUT_URL;
        }
        return logoutUrl;
    }
    public void setLogoutUrl(String logoutUrl) {
        this
}
Copy after login

Determine whether the Session has timed out by getting the User object in the Session. If the Session If it times out, it will be returned according to different request methods. If it is a normal request, the JavaScript script will be returned directly, which can jump the page to other URLs. If it is an Ajax request, a 401 status code will be returned, and sessionTimeout will be added to the returned header. This data will be used on the front end.

The interceptor is configured in the SpringMVC configuration file as follows:


<span style="font-size:14px;"><!-- MVC拦截器 -->
<mvc:interceptors>
    <!-- Web登录拦截器 -->
    <mvc:interceptor>
        <mvc:mapping path="/web/**"/>
        <mvc:exclude-mapping path="/web/index"/><!-- 防止循环重定向到首页 -->
        <mvc:exclude-mapping path="/web/login"/>
        <mvc:exclude-mapping path="/web/logout"/>
        <mvc:exclude-mapping path="/web/doLogin"/>
        <bean class="com.woyi.mhub.interceptor.WebLoginInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors></span><span style="font-size:24px;">
</span>
Copy after login

4. Front-end processing Session timeout

For ordinary requests, the backend returns a JavaScript script, which will be executed immediately. The frontend does not require any processing here.

For Ajax requests, the backend returns a 401 status code and the sessionTimeout set in the header. Here we use jQuery's ajaxComplete callback function, as follows:


// 实现ajax请求时判断Session是否失效 
$(document).ajaxComplete(function(event, response, settings) { 
 var sessionTimeout = response.getResponseHeader("SessionTimeout"); 
 if(sessionTimeout != null && typeof sessionTimeout != "undefined" && sessionTimeout.length > 0){ 
  // 这里写Session超时后的处理方法 
 } 
});
Copy after login

Okay, that's it, users whose Session times out will be processed.

Summarize

The above is the detailed content of Solving the problem of session timeout in Javaweb project. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template