読者です 読者をやめる 読者になる 読者になる

m_shige1979のささやかな抵抗と欲望の日々

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

なんとなく作ったサイト

http://www.it-check-matome.info/


Github(注意すること)

https://github.com/mshige1979

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

フィルタ

起動時、リクエスト、終了時などになんらかの処理を仕込みたい場合に設定する処理のこと
HTTPリクエスト時などで特定のヘッダが存在しない場合は処理を実施しないなどに使用する感じ?

設定方法

  1. Filterをimplemtsしたクラスを実装
  2. @Componentsアノテーションを付与

でイケる感じ

実装

SampleFilter.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;

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

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

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

※これだけでアプリにフィルタが実装される感じらしい

実行ログ

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

2016-12-30 16:44:59.624  INFO 10081 --- [           main] c.e.SpringSampleFilter01Application      : Starting SpringSampleFilter01Application on mshige1979MBA.local with PID 10081 (/Users/matsumotoshigeharu/Documents/workspace/spring_sample_filter01/target/classes started by matsumotoshigeharu in /Users/matsumotoshigeharu/Documents/workspace/spring_sample_filter01)
2016-12-30 16:44:59.626  INFO 10081 --- [           main] c.e.SpringSampleFilter01Application      : No active profile set, falling back to default profiles: default
2016-12-30 16:45:00.109  INFO 10081 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3a93b025: startup date [Fri Dec 30 16:45:00 JST 2016]; root of context hierarchy
2016-12-30 16:45:01.110  INFO 10081 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.ws.config.annotation.DelegatingWsConfiguration' of type [class org.springframework.ws.config.annotation.DelegatingWsConfiguration$$EnhancerBySpringCGLIB$$311b2b8c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-12-30 16:45:01.172  INFO 10081 --- [           main] .w.s.a.s.AnnotationActionEndpointMapping : Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
2016-12-30 16:45:01.634  INFO 10081 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-12-30 16:45:01.651  INFO 10081 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-12-30 16:45:01.653  INFO 10081 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2016-12-30 16:45:01.805  INFO 10081 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-12-30 16:45:01.805  INFO 10081 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1700 ms
2016-12-30 16:45:02.008  INFO 10081 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2016-12-30 16:45:02.010  INFO 10081 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'messageDispatcherServlet' to [/services/*]
2016-12-30 16:45:02.013  INFO 10081 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-12-30 16:45:02.014  INFO 10081 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-12-30 16:45:02.014  INFO 10081 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-12-30 16:45:02.014  INFO 10081 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2016-12-30 16:45:02.014  INFO 10081 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'sampleFilter' to: [/*]
2016-12-30 16:45:02.036  INFO 10081 --- [ost-startStop-1] com.example.config.filter.SampleFilter   : Sample Filter init
2016-12-30 16:45:02.341  INFO 10081 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3a93b025: startup date [Fri Dec 30 16:45:00 JST 2016]; root of context hierarchy
2016-12-30 16:45:02.421  INFO 10081 --- [           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 16:45:02.426  INFO 10081 --- [           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 16:45:02.426  INFO 10081 --- [           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 16:45:02.470  INFO 10081 --- [           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 16:45:02.471  INFO 10081 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-30 16:45:02.514  INFO 10081 --- [           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 16:45:03.050  INFO 10081 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-12-30 16:45:03.122  INFO 10081 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-12-30 16:45:03.127  INFO 10081 --- [           main] c.e.SpringSampleFilter01Application      : Started SpringSampleFilter01Application in 4.188 seconds (JVM running for 5.127)
2016-12-30 16:45:13.216  INFO 10081 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-12-30 16:45:13.216  INFO 10081 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-12-30 16:45:13.233  INFO 10081 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 17 ms
2016-12-30 16:45:13.249  INFO 10081 --- [nio-8080-exec-1] com.example.config.filter.SampleFilter   : Sample Filter doFilter start
2016-12-30 16:45:13.461  INFO 10081 --- [nio-8080-exec-1] com.example.config.filter.SampleFilter   : Sample Filter doFilter end
2016-12-30 16:45:18.987  INFO 10081 --- [nio-8080-exec-2] com.example.config.filter.SampleFilter   : Sample Filter doFilter start
2016-12-30 16:45:18.992  INFO 10081 --- [nio-8080-exec-2] com.example.config.filter.SampleFilter   : Sample Filter doFilter end
2016-12-30 16:45:23.424  INFO 10081 --- [2)-192.168.10.3] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
2016-12-30 16:45:23.424  INFO 10081 --- [2)-192.168.10.3] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3a93b025: startup date [Fri Dec 30 16:45:00 JST 2016]; root of context hierarchy
2016-12-30 16:45:23.427  INFO 10081 --- [2)-192.168.10.3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2016-12-30 16:45:24.489  INFO 10081 --- [ost-startStop-2] com.example.config.filter.SampleFilter   : Sample Filter destroy

動きました
作成するだけで起動するのはちょっと不安な感じもするけど楽といえば楽ですね(^^)

所感

どんな処理を設定するかは今後考えるとしてリクエストの前後などに処理を簡単に設定できるのは結構便利な気がします。
RestAPIなどのトークン制御などに使えるのかも…

広告を非表示にする