Edited at

Spring BootでFilterを実装する - その1

More than 3 years have passed since last update.

Spring Bootではweb.xmlがないのでFilterをどうやって定義するのか色々調べていたら、いくつか実装方法があった。本記事では「その1」として一番シンプルそうな実装をしてみる。


Filterインターフェースの実装クラスを作ってコンテナ登録する(だけ)


LoggingFilter.java

package com.example.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.stereotype.Component;

@Component
public class LoggingFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init!!");
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("Before!!");
chain.doFilter(request, response);
System.out.println("After!!");
}

@Override
public void destroy() {
System.out.println("destroy!!");
}
}


javax.servlet.Filterの実装クラスを作って@Componentアノテーションを付与するだけ。

もちろん、このクラスはComponentScanにひっかかる階層に配置する必要がある。

コンソールを確認してみる。

~省略~

2015-12-16 00:37:20.289 INFO 6164 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.28
2015-12-16 00:37:20.444 INFO 6164 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2015-12-16 00:37:20.449 INFO 6164 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2578 ms
2015-12-16 00:37:21.136 INFO 6164 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2015-12-16 00:37:21.142 INFO 6164 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2015-12-16 00:37:21.143 INFO 6164 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2015-12-16 00:37:21.143 INFO 6164 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2015-12-16 00:37:21.144 INFO 6164 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2015-12-16 00:37:21.147 INFO 6164 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'loggingFilter' to: [/*]
init!!
2015-12-16 00:37:22.124 INFO 6164 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from URL [file:/C:/Development/sts-bundle/workspace/doma-cooperation/target/classes/schema.sql]
2015-12-16 00:37:22.135 INFO 6164 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from URL [file:/C:/Development/sts-bundle/workspace/doma-cooperation/target/classes/schema.sql] in 11 ms.
2015-12-16 00:37:22.137 INFO 6164 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from URL [file:/C:/Development/sts-bundle/workspace/doma-cooperation/target/classes/data.sql]
2015-12-16 00:37:22.142 INFO 6164 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from URL [file:/C:/Development/sts-bundle/workspace/doma-cooperation/target/classes/data.sql] in 3 ms.
2015-12-16 00:37:22.633 INFO 6164 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1c72da34: startup date [Wed Dec 16 00:37:17 JST 2015]; root of context hierarchy
2015-12-16 00:37:22.735 INFO 6164 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/customers],methods=[GET]}" onto public java.util.List<com.example.model.Customer> com.example.controller.CustomerController.getCustomers()
2015-12-16 00:37:22.741 INFO 6164 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2015-12-16 00:37:22.742 INFO 6164 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2015-12-16 00:37:22.779 INFO 6164 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-12-16 00:37:22.779 INFO 6164 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-12-16 00:37:22.831 INFO 6164 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-12-16 00:37:23.367 INFO 6164 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2015-12-16 00:37:23.478 INFO 6164 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2015-12-16 00:37:23.491 INFO 6164 --- [ main] com.example.Application : Started Application in 6.137 seconds (JVM running for 6.794)
2015-12-16 00:37:29.336 INFO 6164 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2015-12-16 00:37:29.336 INFO 6164 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2015-12-16 00:37:29.361 INFO 6164 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 25 ms
Before!!
2015-12-16 00:37:29.459 INFO 6164 --- [nio-8080-exec-1] o.s.doma.jdbc.UtilLoggingJdbcLogger : [DOMA2220] ENTER : 繧ッ繝ゥ繧ケ=[com.example.repository.CustomerRepositoryImpl], 繝。繧ス繝?繝?=[selectAll]
2015-12-16 00:37:29.571 INFO 6164 --- [nio-8080-exec-1] o.s.doma.jdbc.UtilLoggingJdbcLogger : [DOMA2076] SQL繝ュ繧ー : SQL繝輔ぃ繧、繝ォ=[META-INF/com/example/repository/CustomerRepository/selectAll.sql],
select id, name from customers order by id
2015-12-16 00:37:29.644 INFO 6164 --- [nio-8080-exec-1] o.s.doma.jdbc.UtilLoggingJdbcLogger : [DOMA2221] EXIT : 繧ッ繝ゥ繧ケ=[com.example.repository.CustomerRepositoryImpl], 繝。繧ス繝?繝?=[selectAll]
After!!
Before!!
After!!
2015-12-16 00:38:04.274 INFO 6164 --- [2)-192.168.0.12] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
2015-12-16 00:38:04.274 INFO 6164 --- [2)-192.168.0.12] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1c72da34: startup date [Wed Dec 16 00:37:17 JST 2015]; root of context hierarchy
2015-12-16 00:38:04.277 INFO 6164 --- [2)-192.168.0.12] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
destroy!!

ちゃんと出力されてるみたい(文字化けしてるところありますがそれはここでは放置)。

フィルターを複数入れる場合は?その順番は?

そのあたりは次回。