springboot情操陶冶-web配置(二) (3)

本文主要讲解了mvc的springboot自动配置过程,读者主要关注DispatcherServlet组件和消息处理等组件的bean工厂配置即可。如果用户也想自定义去扩展mvc的相关配置,可自行去实现WebMvcConfigurer接口即可,样例如下

package com.example.demo.web.config; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.List; /** * @author nanco * ------------- * ------------- * @create 2018/9/5 **/ public class BootWebMvcConfigurer implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { } @Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { } }

本文也讲述了如果用户想扩展相应的Filter或者Servlet,可使用FilterRegistrationBean/ServletRegistrationBean,样例如下

package com.example.demo.web.config; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author nanco * ------------- * ------------- * @create 2018/9/5 **/ @Configuration public class ServletFilterBeans { // only intercept /simple/ @Bean("simpleServlet") public ServletRegistrationBean<Servlet> simpleServlet() { return new ServletRegistrationBean<>(new SimpleServlet(), "/simple/"); } // intercept /simple、/simple/、/simple/ha etc. @Bean("simpleFilter") public FilterRegistrationBean<Filter> simpleFilter() { FilterRegistrationBean bean = new FilterRegistrationBean<>(); bean.setFilter(new SimpleFilter()); bean.addUrlPatterns("/simple/*"); return bean; } private static class SimpleServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doService path: " + req.getRequestURI()); super.doGet(req, resp); } } private static class SimpleFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { System.out.println("filter path: " + request.getRequestURI()); filterChain.doFilter(request, response); } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wppzdz.html