Spring Boot はデフォルトで Jar パッケージとしてデプロイされるため、デフォルトでは web.xml が存在しないため、以前のように web.xml 構成を使用してサーブレット、フィルター、およびリスナーを使用することはできなくなりましたが、Spring Boot は次の 2 つの方法を提供します。これらのネイティブ Web コンポーネントを登録します。
コンポーネント スキャンによる登録
RegistrationBean による登録
コンポーネント スキャンによる登録
Servlet 3.0 は、次の 3 つのアノテーションを提供します:
@WebServlet: サーブレットの宣言に使用;
@WebFilter: フィルターの宣言に使用;
@WebListener: リスナーの宣言に使用。
これらの注釈は、対応するコンポーネントに直接マークすることができ、web.xml の構成と同じ意味を持ちます。各注釈には web.xml に対応する属性があり、直接構成できるため、面倒な web.xml の構成が不要になります。
これらのネイティブ Web コンポーネントを SpringBoot に登録するには、@ServletComponentScan アノテーションを使用できます。このアノテーションは、@WebServlet、@WebFilter、および @WebListener の 3 つのアノテーションでマークされたコンポーネント クラスをスキャンし、コンテナーに登録します。
注: @ServletComponentScan アノテーションは、スタートアップ クラスまたは構成クラスでのみマークできます。
例
-
@WebServlet アノテーションを使用して、カスタム サーブレットを宣言します。コードは次のとおりです。
パッケージ tangyu9880.servlet;
インポート javax.servlet.ServletException;
インポート javax.servlet.annotation.WebServlet;
インポート javax.servlet.http.HttpServlet
;インポート
javax.servlet.http.HttpServletRequest;インポート java.io.PrintWriter ; // @WebServlet アノテーションを使用してサーブレットを宣言する@WebServlet(name = “myServlet”, urlPatterns = “/myServlet”) public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType(“text/html;charset=UTF-8”); PrintWriter ライター = resp.getWriter(); writer.write(“Spring Boot サーブレット”); ライター.close(); } } -
@WebFilter アノテーションを使用してカスタム フィルターを宣言します。コードは次のとおりです。
package tangyu9880.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
// @WebFilter アノテーションを使用して、カスタム フィルタを宣言します
@WebFilter(urlPatterns = (“/myServlet” ))
public class MyFiler implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("MyFiler initialization"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChange) , ServletException { System.out.println(“MyFiler doFilter”); chain.doFilter(リクエスト、レスポンス); }
@Override
public void destroy() { System.out.println(“MyFiler 销毁”); } } -
@WebListener アノテーションを使用して、カスタム リスナーを宣言します。コードは次のとおりです。
package tangyu9880.Listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
// @WebListener アノテーションを使用して、カスタム リスナーを宣言します
@WebListener
public class MyListener implements ServletContextverListener { @O public void contextInitialized(ServletContextEvent sce) { System.out.println("MyListener は ServletContext の初期化をリッスンします"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("MyListener は ServletContext の破壊をリッスンします"); } }
-
先ほど宣言したServlet、Filter、Listenerをスタートアップクラスに @ServletComponentScan アノテーションでスキャンし、コンテナに登録して利用するコードは以下の通りです。
パッケージ tangyu9880;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication
public class SpringBootServlet {String [] args) { SpringApplication.run(SpringBootServletApplication.class, args); } }
-
Spring Boot を起動すると、コンソール ログは次のようになります。
.____ _ _ _
/\ / ' __ _ ( ) __ _ _ \ \ \
( ( )_ _ | '_ | ' | | ' / ` | \ \ \
\/ )| | )| | | | | || ( | | ) ) )
' | | .__| | | | | | _ , | / / / /
=========| |============ ==| /=/ / / /
:: Spring Boot :: (v2.5.1)
2021-06-23 14:07:04.202 INFO 10200 — [main] nbwww.SpringBootServletApplication : PID 10200 の LAPTOP-C67MRMAG で Java 1.8.0_131 を使用して SpringBootServletApplication を開始しています (D:\spring-boot-servlet\target\classes によって開始された 79330 in D:\spring-boot-servlet)
2021-06-23 14:07:04.205 INFO 10200 — [メイン] nbwww.SpringBootServletApplication : アクティブなプロファイルが設定されていないため、デフォルトのプロファイルにフォールバックします: デフォルト
2021-06-23 14:07 :05.169 INFO 10200 — [main] osbwembedded.tomcat.TomcatWebServer : ポートで初期化された Tomcat: 8080 (http)
2021-06-23 14:07:05.180 INFO 10200 — [main] o.apache.catalina.core。 StandardService : サービスを開始しています [Tomcat]
2021-06-23 14:07:05.180 INFO 10200 — [メイン] org.apache.catalina.core.StandardEngine : サーブレット エンジンを開始しています: [Apache Tomcat/9.0.46]
2021-06-23 14:07:05.245 INFO 10200 — [main] oaccC[Tomcat].[localhost].[/] : Spring 組み込み WebApplicationContext の初期化 2021-06-23 14:07:05.245 INFO 10200 — [main]
wscServletWebServerApplicationContext : ルート WebApplicationContext: 初期化は 984 ミリ秒で完了
MyListener 监听到 ServletContext 初始化
MyFiler 初始化
2021-06-23 14:07:05.543 INFO 10200 — [main] osbwembedded.tomcat.TomcatWebServer : Tomcat がポートで開始されました: 8080 (http)コンテキストパス ''
2021-06-23 14:07:05.550 INFO 10200 — [main] nbwww.SpringBootServletApplication : SpringBootServletApplication を 1.853 秒で開始 (JVM は 2.764 で実行)
MyFiler doFilter
上記のログ出力から、カスタム フィルター Filter とリスナー Listener が有効になっていることがわかります。
- ブラウザは「http://localhost:8080/myServlet」にアクセスし、結果は以下の通りです。
Spring Boot Register サーブレット
図 1: Spring Boot Register サーブレット
上の図からわかるように、カスタム サーブレットも有効になっています。
RegistrationBean を使用した登録
構成クラスで RegistrationBean を使用してネイティブ Web コンポーネントを登録することもできますが、この方法はアノテーション メソッドよりも面倒です。この方法で登録されたネイティブ Web コンポーネントは、@WebServlet、@WebListener、@WebListener などのアノテーションを使用する必要がなくなりました。
RegistrationBean は、コンポーネントをサーブレット コンテナーに登録するための抽象クラスです。Spring は、サーブレット、フィルター、およびリスナーをそれぞれ登録するための 3 つの実装クラスを提供します。
ServletRegistrationBean: サーブレット登録クラス
FilterRegistrationBean: フィルター登録クラス
ServletListenerRegistrationBean: リスナー登録クラス
@Bean アノテーションを使用して、ServletRegistrationBean、FilterRegistrationBean、および ServletListenerRegistrationBean を構成クラスの Spring コンテナーに追加し、それらを介してカスタム Servlet、Filter、および Listener コンポーネントをコンテナーに登録できます。
例 2
-
パッケージtangyu9880.servlet
;
import javax.servlet.ServletException;
javax.servlet.http.HttpServlet をインポートします。
import javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse をインポートします。
import java.io.IOException;
java.io.PrintWriter をインポートします。
public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType(“text/html;charset=UTF-8”);
PrintWriter ライター = resp.getWriter();
writer.write(“Spring Boot サーブレット”);
ライター.close();
}
} -
カスタム フィルターを作成します。コードは次のとおりです。
package tangyu9880.filter;
import javax.servlet.*;
import java.io.IOException;
public class MyFiler implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("MyFiler initialization"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println(“MyFiler doFilter”); chain.doFilter(request, response); } @Override public) void destroy( System .out.println("MyFiler が破棄されました"); } }
-
カスタム リスナーを作成します。コードは次のとおりです。
package tangyu9880.Listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
//ServletContext の初期化と破棄のプロセスを監視
public class MyListener implements ServletContextListener { @Override public void contextInitialized(ServletContext.printoutEvent) { "MyListener はServletContext の初期化"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("MyListener は ServletContext の破壊をリッスンします"); } }
-
構成クラス MyConfig を作成し、@Bean アノテーションを使用して ServletRegistrationBean、FilterRegistrationBean、ServletListenerRegistrationBean を Spring コンテナーに追加し、それらを使用してカスタム Servlet、Filter、Listener をそれぞれ登録します。サンプル コードは次のとおりです。
パッケージ tangyu9880.config;
インポート tangyu9880.Listener.MyListener;
インポート tangyu9880.filter.MyFiler;
インポート tangyu9880.servlet.MyServlet;
インポート org.springframework.boot.web.servlet.FilterRegistrationBean;
インポート org.springframework.boot.ServletListenerRegistrationBean;
インポート org .springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@Configuration
public class MyConfig { /**- サーブレットを登録する
- @return
/
@Bean
public ServletRegistrationBean servletRegistrationBean() { MyServlet myServlet = new MyServlet(); return new ServletRegistrationBean(myServlet, “/myServlet”); } /
* - 登録フィルター
- @return
/
@Bean
public FilterRegistrationBean filterRegistrationBean() { MyFiler myFiler = new MyFiler(); FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFiler); //フィルタがフィルタするために必要な URL を登録するfilterRegistrationBean.setUrlPatterns(Arrays.asList(“/myServlet ” )); return filterRegistrationBean; } /
* - リスナーを登録する
- @return
*/
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean() { MyListener myListener = new MyListener(); 新しい ServletListenerRegistrationBean(myListener) を返します。} }
-
Spring Boot を起動すると、コンソール ログは次のようになります。
.____ _ _ _
/\ / ' __ _ ( ) __ _ _ \ \ \
( ( )_ _ | '_ | ' | | ' / ` | \ \ \
\/ )| | )| | | | | || ( | | ) ) )
' | | .__| | | | | | _ , | / / / /
=========| |============ ==| /=/ / / /
:: Spring Boot :: (v2.5.1)
2021-06-23 14:39:16.338 INFO 8684 — [main] nbwww.SpringBootServletApplication : PID 8684 の LAPTOP-C67MRMAG で Java 1.8.0_131 を使用して SpringBootServletApplication を開始しています (D:\spring-boot-servlet\target\classes によって開始された 79330 D:\spring-boot-servlet 内)
2021-06-23 14:39:16.340 INFO 8684 — [メイン] nbwww.SpringBootServletApplication : アクティブなプロファイルが設定されていないため、デフォルトのプロファイルにフォールバックします: デフォルト
2021-06-23 14:39 :17.059 情報 8684 — [メイン] osbwembedded.tomcat.TomcatWebServer : ポートで初期化された Tomcat: 8080 (http)
2021-06-23 14:39:17.069 情報 8684 — [メイン] o.apache.catalina.core。 StandardService : サービスを開始しています [Tomcat]
2021-06-23 14:39:17.070 INFO 8684 — [メイン] org.apache.catalina.core.StandardEngine : サーブレット エンジンを開始しています: [Apache Tomcat/9.0.46]
2021-06-23 14:39:17.138 INFO 8684 — [main] oaccC[Tomcat].[localhost].[/] : Spring 組み込み WebApplicationContext の初期化 2021-06-23 14:39:17.138 INFO 8684 — [main]
wscServletWebServerApplicationContext : ルート WebApplicationContext: 初期化は 766 ミリ秒で完了
MyListener 监听到 ServletContext 初始化
MyFiler 初始化
2021-06-23 14:39:17.390 INFO 8684 — [main] osbwembedded.tomcat.TomcatWebServer : Tomcat がポートで開始されました: 8080 (http)コンテキスト パス ''
2021-06-23 14:39:17.396 INFO 8684 — [main] nbwww.SpringBootServletApplication : SpringBootServletApplication を 1.379 秒で開始しました (JVM は 2.19 で実行されています)
上記のログ出力から、カスタム フィルター Filter とリスナー Listener が有効になっていることがわかります。
- ブラウザは「http://localhost:8080/myServlet」にアクセスし、結果は下図のようになります。
Spring Boot Register サーブレット
図 1: Spring Boot Register サーブレット
上の図からわかるように、カスタム サーブレットも登録され、有効になっています。