栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot: Web原生组件注入(Servlet、Filter、Listener) ---- 15

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot: Web原生组件注入(Servlet、Filter、Listener) ---- 15

ssss我们依旧以SpringBoot官网的官方文档为准学习。Spring Boot Features ==> 7.Developing Web Applications ==> 7.4 Embedded Servlet Container Support

      • 使用Servlet API
        • 1 @WebServlet + @ServletComponentScan
        • 2 @WebFilter + @ServletComponentScan
        • @WebListener + @ServletComponentScan
      • 对Servlet API替代:使用RegistrationBean
        • ①、**ServletRegistrationBean** ②、**FilterRegistrationBean** ③、**ServletListenerRegistrationBean**
      • 为什么原生Servlet没有被Spring拦截器拦截?
        • DispatchServlet 如何注册进来 ==》DispatcherServletAutoConfiguration
        • 原因分析:多个Servlet都能处理同一层路径,遵循精确优先原则:(网图)

使用Servlet API 1 @WebServlet + @ServletComponentScan

@ServletComponentScan(basePackages = “com.atguigu.webadmin”) :指定原生Servlet组件都放在那里

@WebServlet(urlPatterns = “/my”):效果:===> 直接响应,没有经过Spring的拦截器

@WebServlet(urlPatterns = "/my")
public class MyServlet  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("6666");
    }
}
========================================================================================================
// 指定原生Servlet组件存放地点
@ServletComponentScan(basePackages = "com.atguigu.webadmin")
@SpringBootApplication
public class Boot05WebAdminApplication {

    public static void main(String[] args) {
        SpringApplication.run(Boot05WebAdminApplication.class, args);
    }
}

ssss结果:sdsdsdsdsss

2 @WebFilter + @ServletComponentScan
@Slf4j
							// 拦截静态资源,单 * 是Servlet写法,** 是SpringBoot写法
@WebFilter(urlPatterns = {"/css/*", "images/*"})
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("MyFilter初始化完成");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("MyFilter内部逻辑!");
        filterChain.doFilter(servletRequest,servletResponse);  //放行
    }
    @Override
    public void destroy() {
        log.info("MyFilter销毁");
    }
}
@WebListener + @ServletComponentScan
@Slf4j
@WebListener
public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("MyServletContextListener监听到项目初始化完成");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("MyServletContextListener监听到项目销毁");
    }
}
对Servlet API替代:使用RegistrationBean ①、ServletRegistrationBean ②、FilterRegistrationBean ③、ServletListenerRegistrationBean
@Configuration
public class MyRegistorConfig {
    @Bean
    public ServletRegistrationBean myServlet(){
        MyServlet myServlet = new MyServlet();
        return new ServletRegistrationBean(myServlet,"/my","/my02");
    }
    @Bean
    public FilterRegistrationBean myFilter(){
        MyFilter myFilter = new MyFilter();
   //     return new FilterRegistrationBean(myFilter,myServlet());   拦截servlet的路径 
        FilterRegistrationBean myFilterFilterRegistrationBean = new FilterRegistrationBean<>(myFilter);
        myFilterFilterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
        return myFilterFilterRegistrationBean;
    }
    @Bean
    public ServletListenerRegistrationBean myListner(){
        MyServletContextListener myServletContextListener = new MyServletContextListener();
        return new ServletListenerRegistrationBean(myServletContextListener);
    }
}
===================================================================================================================
原来写的三个Servlet API 的类 的注解 @WebFilter @WebListener @Servlet 可以不用写,而是用xxxRegistrationBean来替代。
为什么原生Servlet没有被Spring拦截器拦截?

ssss目前容器中有两个Servlet:

ssddsdssss MyServlet ==》/myservlet

ssdsdsdsss DispatcherServlet ==》/

DispatchServlet 如何注册进来 ==》DispatcherServletAutoConfiguration

ssss①、容器中自动配置了 DispatcherServlet 属性绑定到 WebMvcProperties;对应的配置文件配置项是 spring.mvc。

@Bean(
    name = {"dispatcherServlet"}
)
public DispatcherServlet dispatcherServlet(WebMvcProperties webMvcProperties) {
    DispatcherServlet dispatcherServlet = new DispatcherServlet();
    dispatcherServlet.setDispatchOptionsRequest(webMvcProperties.isDispatchOptionsRequest());
    dispatcherServlet.setDispatchTraceRequest(webMvcProperties.isDispatchTraceRequest());
    dispatcherServlet.setThrowExceptionIfNoHandlerFound(webMvcProperties.isThrowExceptionIfNoHandlerFound());
    dispatcherServlet.setPublishEvents(webMvcProperties.isPublishRequestHandledEvents());
    dispatcherServlet.setEnableLoggingRequestDetails(webMvcProperties.isLogRequestDetails());
    return dispatcherServlet;
}
=================》我们可以看出DispatcherServlet 的属性绑定的是webMvcProperties类:
	@ConfigurationProperties(
	    prefix = "spring.mvc"
	)
	public class WebMvcProperties {
	    private org.springframework.validation.DefaultMessageCodesResolver.Format messageCodesResolverFormat;
	    ===================》说明webMvcProperties类绑定的配置文件是 prefix = "spring.mvc".

ssss②、通过 ServletRegistrationBean 把 DispatcherServlet 配置进来。

 DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet, 
												 webMvcProperties.getServlet().getPath());
=========》
    public String getPath() { return this.path;}
    	 =========》String path = "/";   
     			=========》因此DispatcherServlet 的处理路径是"/".

ssss修改DispatcherServlet的处理路径,默认是 /,比如改为其下的mvc包:

spring:
	mvc:
		servlet:
			path: /mvc/
原因分析:多个Servlet都能处理同一层路径,遵循精确优先原则:(网图)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/532118.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号