Home Java javaTutorial Solving the problem of session timeout in Javaweb project

Solving the problem of session timeout in Javaweb project

Sep 21, 2017 am 10:16 AM
javaweb session web

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

What are the differences between JavaScript and PHP cookies? What are the differences between JavaScript and PHP cookies? Sep 02, 2023 pm 12:29 PM

JavaScriptCookies Using JavaScript cookies is the most effective way to remember and track preferences, purchases, commissions and other information. Information needed for a better visitor experience or website statistics. PHPCookieCookies are text files that are stored on client computers and retained for tracking purposes. PHP transparently supports HTTP cookies. How do JavaScript cookies work? Your server sends some data to your visitor's browser in the form of a cookie. Browsers can accept cookies. If present, it will be stored on the visitor's hard drive as a plain text record. Now, when a visitor reaches another page on the site

How to implement form validation for web applications using Golang How to implement form validation for web applications using Golang Jun 24, 2023 am 09:08 AM

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

what does web mean what does web mean Jan 09, 2024 pm 04:50 PM

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages ​​to enable data exchange and information sharing between different computers.

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

See all articles