1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Webアプリケーション始動時/終了時に呼び出す処理を実装する

Posted at

Webアプリケーション始動時に処理を実行したい

Webアプリケーションを実装してアプリケーション始動時に実行した処理があったので方法を調べてみました。以前はWebSphereにはStartUpBeanなるものがあった記憶が、、、、

ServletContextListnerの実装

どうやらServletContextListnerインターフェースを実装したクラスを作成し、Web.xmlに登録しておけば良いようです。

SampleListener.java
package test;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class SampleListener implements ServletContextListener {


  @Override
  public void contextDestroyed(ServletContextEvent arg0) {
 //アプリケーション終了時のコードを記述する
  }


  @Override
  public void contextInitialized(ServletContextEvent arg0) {
  //アプリケーション始動時のコードを記述する
  }
}

Web.xmlへの記述は以下の通り

web.xml
<listener>
<listener-class>test.SampleListner</listener-class>
</listener>

実際にデプロイしてみたところ、処理が呼ばれていることを確認しました。引数としてServletContextEventが渡されるため、コンテキスト・ルートを取得するなどの処理も書くことができます。

まとめ

Webアプリケーション始動時・終了時に実行する処理を実装したい場合には、ServletContextListenerインターフェースを実装したクラスを作成し、Web.xmlにリスナー・クラスとして登録すればOKです。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?