m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

Spring Bootで複数のフィルターを設定する

フィルタ内で全て1つでまとめるより

複数に分けたほうが管理し易いよね

やること

  1. Filterをimplementsしたクラスを作成
  2. @Componentsアノテーションは設定しない
  3. WebMvcConfigurerAdapterを継承したクラスで使用するフィルタを設定

フィルタ準備

Sample1Filter.java
package com.example.config.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

public class Sample1Filter implements Filter {
	
	private static final Logger logger = LoggerFactory.getLogger(Sample1Filter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 起動時に実行される
		logger.info("Sample1 Filter init");
	}
	 
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// リクエスト発行時に実行される
		logger.info("Sample1 Filter doFilter start");
		chain.doFilter(request, response);
		logger.info("Sample1 Filter doFilter end");
	}

	@Override
	public void destroy() {
		// 終了時に実行される
		logger.info("Sample1 Filter destroy");
	}
	
}
Sample2Filter.java
package com.example.config.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

public class Sample2Filter implements Filter {
	
	private static final Logger logger = LoggerFactory.getLogger(Sample2Filter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 起動時に実行される
		logger.info("Sample2 Filter init");
	}
	 
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// リクエスト発行時に実行される
		logger.info("Sample2 Filter doFilter start");
		chain.doFilter(request, response);
		logger.info("Sample2 Filter doFilter end");
	}

	@Override
	public void destroy() {
		// 終了時に実行される
		logger.info("Sample2 Filter destroy");
	}
	
}

フィルタ設定用クラス

WebConfig.java
package com.example.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.example.config.filter.Sample1Filter;
import com.example.config.filter.Sample2Filter;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
	
	@Bean
	public FilterRegistrationBean sampleFilter1() {		
		FilterRegistrationBean bean = new FilterRegistrationBean();
		bean.setFilter(new Sample1Filter());
		bean.setOrder(2);
		return bean;
	}
	
	@Bean
	public FilterRegistrationBean sampleFilter2() {		
		FilterRegistrationBean bean = new FilterRegistrationBean();
		bean.setFilter(new Sample2Filter());
		bean.setOrder(1);
		return bean;
	}
	
}

実行結果

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.3.RELEASE)

2016-12-30 17:23:45.163  INFO 10234 --- [           main] c.e.SpringSampleFilter01Application      : Starting SpringSampleFilter01Application on mshige1979MBA.local with PID 10234 (/Users/matsumotoshigeharu/Documents/workspace/spring_sample_filter01/target/classes started by matsumotoshigeharu in /Users/matsumotoshigeharu/Documents/workspace/spring_sample_filter01)
2016-12-30 17:23:45.167  INFO 10234 --- [           main] c.e.SpringSampleFilter01Application      : No active profile set, falling back to default profiles: default
2016-12-30 17:23:45.569  INFO 10234 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3a93b025: startup date [Fri Dec 30 17:23:45 JST 2016]; root of context hierarchy
2016-12-30 17:23:47.049  INFO 10234 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.ws.config.annotation.DelegatingWsConfiguration' of type [class org.springframework.ws.config.annotation.DelegatingWsConfiguration$$EnhancerBySpringCGLIB$$9e478f9c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-12-30 17:23:47.130  INFO 10234 --- [           main] .w.s.a.s.AnnotationActionEndpointMapping : Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
2016-12-30 17:23:47.672  INFO 10234 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-12-30 17:23:47.688  INFO 10234 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-12-30 17:23:47.689  INFO 10234 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2016-12-30 17:23:47.821  INFO 10234 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-12-30 17:23:47.822  INFO 10234 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2258 ms
2016-12-30 17:23:48.109  INFO 10234 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-12-30 17:23:48.110  INFO 10234 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-12-30 17:23:48.110  INFO 10234 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-12-30 17:23:48.110  INFO 10234 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2016-12-30 17:23:48.110  INFO 10234 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'sample2Filter' to: [/*]
2016-12-30 17:23:48.110  INFO 10234 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'sample1Filter' to: [/*]
2016-12-30 17:23:48.111  INFO 10234 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2016-12-30 17:23:48.112  INFO 10234 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'messageDispatcherServlet' to [/services/*]
2016-12-30 17:23:48.145  INFO 10234 --- [ost-startStop-1] com.example.config.filter.Sample2Filter  : Sample2 Filter init
2016-12-30 17:23:48.146  INFO 10234 --- [ost-startStop-1] com.example.config.filter.Sample1Filter  : Sample1 Filter init
2016-12-30 17:23:48.481  INFO 10234 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3a93b025: startup date [Fri Dec 30 17:23:45 JST 2016]; root of context hierarchy
2016-12-30 17:23:48.567  INFO 10234 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/sample1/index],methods=[GET]}" onto public java.lang.String com.example.controller.Sample1Controller.index(org.springframework.ui.Model)
2016-12-30 17:23:48.571  INFO 10234 --- [           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)
2016-12-30 17:23:48.572  INFO 10234 --- [           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,javax.servlet.http.HttpServletResponse)
2016-12-30 17:23:48.634  INFO 10234 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-30 17:23:48.635  INFO 10234 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-30 17:23:48.701  INFO 10234 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-30 17:23:49.657  INFO 10234 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-12-30 17:23:49.792  INFO 10234 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-12-30 17:23:49.798  INFO 10234 --- [           main] c.e.SpringSampleFilter01Application      : Started SpringSampleFilter01Application in 5.262 seconds (JVM running for 5.969)
2016-12-30 17:23:58.031  INFO 10234 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-12-30 17:23:58.032  INFO 10234 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-12-30 17:23:58.072  INFO 10234 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 40 ms
2016-12-30 17:23:58.087  INFO 10234 --- [nio-8080-exec-1] com.example.config.filter.Sample2Filter  : Sample2 Filter doFilter start
2016-12-30 17:23:58.088  INFO 10234 --- [nio-8080-exec-1] com.example.config.filter.Sample1Filter  : Sample1 Filter doFilter start
2016-12-30 17:23:58.409  INFO 10234 --- [nio-8080-exec-1] com.example.config.filter.Sample1Filter  : Sample1 Filter doFilter end
2016-12-30 17:23:58.409  INFO 10234 --- [nio-8080-exec-1] com.example.config.filter.Sample2Filter  : Sample2 Filter doFilter end
2016-12-30 17:24:02.681  INFO 10234 --- [2)-192.168.10.3] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
2016-12-30 17:24:02.682  INFO 10234 --- [2)-192.168.10.3] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3a93b025: startup date [Fri Dec 30 17:23:45 JST 2016]; root of context hierarchy
2016-12-30 17:24:02.684  INFO 10234 --- [2)-192.168.10.3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2016-12-30 17:24:03.757  INFO 10234 --- [ost-startStop-2] com.example.config.filter.Sample2Filter  : Sample2 Filter destroy
2016-12-30 17:24:03.757  INFO 10234 --- [ost-startStop-2] com.example.config.filter.Sample1Filter  : Sample1 Filter destroy

こんな感じですかね…

所感

なんとなくDIなどの動きはわかってきたけどBeanの仕組みがいまいちわかってない(´・ω・`)
データの流れを上手く把握しないと記載方法などに影響ができるの少しずつでも理解しておく必要がある。
日本語のマニュアルどっかにないかな〜