Home Java javaTutorial Detailed explanation of the causes of Session timeout problem in SpringBoot

Detailed explanation of the causes of Session timeout problem in SpringBoot

May 10, 2018 pm 01:49 PM
session springboot question

This article mainly introduces the detailed explanation of the Session timeout principle in SpringBoot. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

1: Preface:

If there is no operation after logging in to the payment background for a period of time, , you always need to log in again before you can continue to access the page. The reason for this problem is that the session times out. After debugging the code, it was found that the session time out is 1800s. That is to say, when there is no operation within 1800 seconds, the session will time out. So how is this timeout set? Then how to reset this timeout? How does the system determine when the session has timed out? Next, we will answer them one by one.

2: How is the system session timeout set by default?

Explanation: The method to obtain the session timeout is "request.getSession().getMaxInactiveInterval()", but the parameter for setting the timeout in tomcat is "sessionTimeout", then How are they connected?

Step 1: Load the sessionTimeout parameter.

1. Project operation initialization loads the "org.springframework.boot.autoconfigure.web.ServerProperties" class through the "@ConfigurationProperties" annotation.

//springBoot中默认的配置文件为"application.yml"或者"application.perties"文件,也就是说server是其中的一个配置参数。
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties
  implements EmbeddedServletContainerCustomizer, EnvironmentAware, Ordered {
//代码
}
Copy after login

2. The "ServerProperties" in the above class inherits from the "EmbeddedServletContainerCustomizer" interface. Rewrite the customize method, and then "push up" in this method to find the "AbstractConfigurableEmbeddedServletContainer" class.

@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
 //多个参数判断,如果在application中没配置的情况下都是null
 if (getPort() != null) {
  container.setPort(getPort());
 }
 ...//n多个参数判断,
 //以下的代码就是重点,因为是tomcat容器,所以以下条件为“真”,经过一系列的查找父类或者实现接口即可找到抽象类“AbstractConfigurableEmbeddedServletContainer”
 //public class TomcatEmbeddedServletContainerFactory extends AbstractEmbeddedServletContainerFactory implements ResourceLoaderAware
 //public abstract class AbstractEmbeddedServletContainerFactory extends AbstractConfigurableEmbeddedServletContainer implements EmbeddedServletContainerFactory 
 if (container instanceof TomcatEmbeddedServletContainerFactory) {
  getTomcat().customizeTomcat(this,
   (TomcatEmbeddedServletContainerFactory) container);
 }
//以上代码执行完成之后,实际上已经有对应的session所有的默认参数,之后通过下面方法,将所有参数放入对应的容器中。第3、4步就是设置过程
 container.addInitializers(new SessionConfiguringInitializer(this.session));
}
Copy after login

3. You can finally find the relevant settings of "timeout time" in the "AbstractConfigurableEmbeddedServletContainer" class

//重要代码
//45行
private static final int DEFAULT_SESSION_TIMEOUT = (int) TimeUnit.MINUTES
  .toSeconds(30);
//66行
private int sessionTimeout = DEFAULT_SESSION_TIMEOUT;
 
@Override
public void setSessionTimeout(int sessionTimeout) {
 this.sessionTimeout = sessionTimeout;
}
//171-188行
@Override
public void setSessionTimeout(int sessionTimeout, TimeUnit timeUnit) {
 Assert.notNull(timeUnit, "TimeUnit must not be null");
 this.sessionTimeout = (int) timeUnit.toSeconds(sessionTimeout);
}

/**
 * Return the session timeout in seconds.
 * @return the timeout in seconds
 */
public int getSessionTimeout() {
 return this.sessionTimeout;
}
Copy after login

4. Perform step 2 of "Container.addInitializers(new SessionConfiguringInitializer(this.session ))" loads all configuration parameters.

public static class Session {

 /**
 * Session timeout in seconds.
 */
 private Integer timeout;

 public Integer getTimeout() {
  return this.timeout;
 }
//将session超时时间设置进来
 public void setTimeout(Integer sessionTimeout) {
  this.timeout = sessionTimeout;
 }
Copy after login

Step 2: Assign the above timeout period to the "MaxInactiveInterval" parameter.

Note: Since all the parameters required by tomcat above have been loaded, tomcat will be run next. I will not go into details here and go directly to the description of tomcat startup and loading parameters. The method calling process in the "TomcatEmbeddedServletContainerFactory" class is as follows:

getEmbeddedServletContainer--》prepareContext--》configureContext--》configureSession--》getSessionTimeoutInMinutes.

1. Call configureSession to set the Session configuration parameters of tomcat.

//以下代码
private void configureSession(Context context) {
 long sessionTimeout = getSessionTimeoutInMinutes();
 context.setSessionTimeout((int) sessionTimeout);
 Manager manager = context.getManager();
 if (manager == null) {
  manager = new StandardManager();
  //此处即为设置相应的参数的位置。之后会调用StandardContext类的setManger(Manager)方法,在setManger中会调用"manager.setContext(this)"
  context.setManager(manager);
 }
}
//计算超时时间为分钟(注意:此处会将之前的1800秒,转换为30分钟)。可以看出最终的时间结果是个整数的分钟类型,也就是说如果设置的超时时间(单位为秒)不是60的倍数,也会最终转换为60的倍数,并且最小超时时间设置的是60秒。
private long getSessionTimeoutInMinutes() {
 long sessionTimeout = getSessionTimeout();
 if (sessionTimeout > 0) {
  sessionTimeout = Math.max(TimeUnit.SECONDS.toMinutes(sessionTimeout), 1L);
 }
 return sessionTimeout;
}
Copy after login

2. Finally, assign SessionTimeout to MaxInactiveInterval. Finally completed the session timeout setting.

//以下代码
@Override
public void setContext(Context context) {
 //省略其余设置代码,直接重新设置Session超时时间,此时又将上面的分钟单位转为秒。此时终于给Sesseion设置了默认超时时间。
 if (this.context != null) {
  setMaxInactiveInterval(this.context.getSessionTimeout() * 60);
  this.context.addPropertyChangeListener(this);
 }
}
Copy after login

3: What if the timeout is customized?

In fact, from the above process, it is not difficult to see that you only need to find the corresponding Session parameters in the "org.springframework.boot.autoconfigure.web.ServerProperties" class. Initialize and let it load to complete the setting.

/**
 * Get the session timeout.
 * @return the session timeout
 * @deprecated since 1.3.0 in favor of {@code session.timeout}.
 */
@Deprecated
@DeprecatedConfigurationProperty(replacement = "server.session.timeout")
public Integer getSessionTimeout() {
 return this.session.getTimeout();
}
Copy after login

So just configure "server.session.timeout" in the application. The parameter type is long type and the unit is "seconds".

Four: How does the running program determine the session timeout?

It's actually very simple: you just need to compare the time of the same sessionequest request with the previous request time, and find that the difference between the two values ​​is greater than MaxInactiveInterval The value can be.

//判断是否超时
@Override
public boolean isValid() {
 //省略多个条件判断
 if (maxInactiveInterval > 0) {
  //判断此session空闲时间是否比maxInactiveInterval大,如果大的情况下,session就超时
  int timeIdle = (int) (getIdleTimeInternal() / 1000L);
  if (timeIdle >= maxInactiveInterval) {
   expire(true);
  }
 }
 return this.isValid;
}
//将上次访问时间和当前时间比较,拿到空闲时间值
@Override
public long getIdleTimeInternal() {
 long timeNow = System.currentTimeMillis();
 long timeIdle;
 if (LAST_ACCESS_AT_START) {
  timeIdle = timeNow - lastAccessedTime;
 } else {
  timeIdle = timeNow - thisAccessedTime;
 }
 return timeIdle;
}
Copy after login

Note:

So in order to ensure that the session timeout is longer, you can configure the "server.session.timeout" parameter in the application configuration file. The parameter unit is "seconds" ”, if the parameter is not an integer multiple of 60, it will be converted to an integer multiple of 60 (see 2: How the system sets the timeout, the algorithm in “1” in step 2). If it is less than one minute, it will be converted to 60 seconds.

Extension:

In fact, you can also directly override the customize method of EmbeddedServletContainerCustomizer for assignment.

 @Bean
 public EmbeddedServletContainerCustomizer containerCustomizer(){
  return new EmbeddedServletContainerCustomizer() {
   @Override
   public void customize(ConfigurableEmbeddedServletContainer container) {
     container.setSessionTimeout(600);//单位为S
   }
  };
 }
Copy after login

The above is the detailed content of Detailed explanation of the causes of Session timeout problem in SpringBoot. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

Clustering effect evaluation problem in clustering algorithm Clustering effect evaluation problem in clustering algorithm Oct 10, 2023 pm 01:12 PM

The clustering effect evaluation problem in the clustering algorithm requires specific code examples. Clustering is an unsupervised learning method that groups similar samples into one category by clustering data. In clustering algorithms, how to evaluate the effect of clustering is an important issue. This article will introduce several commonly used clustering effect evaluation indicators and give corresponding code examples. 1. Clustering effect evaluation index Silhouette Coefficient Silhouette coefficient evaluates the clustering effect by calculating the closeness of the sample and the degree of separation from other clusters.

Teach you how to diagnose common iPhone problems Teach you how to diagnose common iPhone problems Dec 03, 2023 am 08:15 AM

Known for its powerful performance and versatile features, the iPhone is not immune to the occasional hiccup or technical difficulty, a common trait among complex electronic devices. Experiencing iPhone problems can be frustrating, but usually no alarm is needed. In this comprehensive guide, we aim to demystify some of the most commonly encountered challenges associated with iPhone usage. Our step-by-step approach is designed to help you resolve these common issues, providing practical solutions and troubleshooting tips to get your equipment back in peak working order. Whether you're facing a glitch or a more complex problem, this article can help you resolve them effectively. General Troubleshooting Tips Before delving into specific troubleshooting steps, here are some helpful

How to solve the problem that jQuery cannot obtain the form element value How to solve the problem that jQuery cannot obtain the form element value Feb 19, 2024 pm 02:01 PM

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

What are the differences between SpringBoot and SpringMVC? What are the differences between SpringBoot and SpringMVC? Dec 29, 2023 am 10:46 AM

What is the difference between SpringBoot and SpringMVC? SpringBoot and SpringMVC are two very popular Java development frameworks for building web applications. Although they are often used separately, the differences between them are obvious. First of all, SpringBoot can be regarded as an extension or enhanced version of the Spring framework. It is designed to simplify the initialization and configuration process of Spring applications to help developers

How to solve the problem of the start menu that cannot be used after win11 installation How to solve the problem of the start menu that cannot be used after win11 installation Jan 06, 2024 pm 05:14 PM

Many users have tried to update the win11 system, but found that the start menu cannot be used after the update. This may be because there is a problem with the latest update. We can wait for Microsoft to fix or uninstall these updates to solve the problem. Let's take a look at it together. Solution. What to do if the start menu cannot be used after win11 is installed. Method 1: 1. First open the control panel in win11. 2. Then click the "Uninstall a program" button below the program. 3. Enter the uninstall interface and find "View installed updates" in the upper left corner. 4. After entering, you can view the update time in the update information and uninstall all recent updates. Method 2: 1. In addition, we can also directly download the win11 system without updates. 2. This is a product without the most

See all articles