10
19

More than 5 years have passed since last update.

Spring Boot - セッションタイムアウト時間の設定方法

Last updated at Posted at 2018-07-28

Spring Bootでセッションタイムアウト時間を設定する方法についての覚書。

環境とか

  • Spring Boot v2.0.3 (※Spring Sessionは未使用)

設定方法

JAR ビルドの場合

application.properties に以下の設定を追加するだけ。
ちなみに、server.servlet配下の設定は組み込みのアプリケーションサーバに対する設定らしい。

application.properties
server.servlet.session.timeout=30

WAR ビルドの場合

application.properties の server.servlet 配下の設定は組み込みのアプリケーションサーバに対する設定なので、warデプロイの場合は使用されない。warデプロイの場合は以下のどちらかの方法で設定することができる。

web.xml で設定する方法

web.xml を作成して設定する。

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

</web-app>

TOMCAT_HOME/conf/web.xml でアプリケーションサーバに対するデフォルトのセッションタイムアウト設定することが可能。ただし、ほとんどの場合はアプリケーション個別にセッションタイムアウトを設定したいことのほうが多いと思う。その場合は、アプリケーションプロジェクトに src/main/webapp/WEB-INF/web.xml を作成する。

ちなみに、eclipse(STS) を使用している場合は、プロジェクトのプロパティーの「デプロイメント・アセンブリー」で、/src/main/webapp を追加しておくとWTPでアプリケーションを起動する際にも、作成したweb.xmlが使用されてハッピー。

HttpSessionListener で設定する方法

原始的な方法だけど、Session生成/破棄時に実行される、HttpSessionListenerで設定する方法もある。
ただし、単にセッションタイムアウト時間を設定したいだけの場合は冗長な気がするので web.xml で指定したほうがよいと思う。

HttpSessionListenerImpl.java
public class HttpSessionListenerImpl implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        // セッションタイムアウト時間を秒で設定
        session.setMaxInactiveInterval(1800);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
    }
}
WebAppConfig.java
@Configuration
@Import({HttpSessionListenerImpl.class})
public class WebAppConfig {
    // ...
}
10
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
19