SpringBoot28 web原生组件注入servlet、filter、listener
方式一、使用servlet Api
@ServletComponentScan(basePackages = "com.bootweb") :指定扫描原生Servlet组件都放在那里;放在主方法文件上。
@WebServlet(urlPatterns = "/my"):效果:直接响应,没有经过Spring的拦截器?
@WebFilter(urlPatterns={"/css/*","/images/*"})
@WebListener
推荐可以这种方式;
主方法类:
@ServletComponentScan(basePackages = "com.bootweb") //缺省则是主配置类所在目录下的所有 @SpringBootApplication public class BootwebApplication { public static void main(String[] args) { SpringApplication.run(BootwebApplication.class, args); } }
自定义的原生组件:
@WebServlet("/my")
public class MyServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
resp.getWriter().write("6666");
}
}
//==============
@Slf4j
@WebFilter(urlPatterns = {"/css/*","/images"})//单* 是servlet中的写法,** 是spring中的写法
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("MyFilter 初始化完成");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
log.info("MyFilter 开始工作");
chain.doFilter(request,response);
}
@Override
public void destroy() {
log.info("MyFilter 销毁");
}
}
//=======
@Slf4j
@WebListener
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
log.info("MyListener监听到项目启动");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
log.info("MyListener监听到项目销毁");
}
}
方式二、使用XXXRegistrationBean
ServletRegistrationBean, FilterRegistrationBean, and ServletListenerRegistrationBean
自定义config,注入上述三个@BEAN
@Configuration public class MyRegisterConfig { @Bean public ServletRegistrationBean newServlet(){ MyServlet myServlet = new MyServlet(); return new ServletRegistrationBean(myServlet,"/my","/my2"); } @Bean public FilterRegistrationBean newFilter(){ MyFilter myFilter = new MyFilter(); // return new FilterRegistrationBean(myFilter,newServlet()); FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter); filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/my2")); return filterRegistrationBean; } @Bean public ServletListenerRegistrationBean newListener(){ MyListener myListener = new MyListener(); return new ServletListenerRegistrationBean(myListener); } }
遗留问题:
proxyBeanMethod=true/false 的作用是什么?
上述执行过程,为什么没有经过之前定义的拦截器?
现在系统中有两个servlet
1、自定义的 路径 “/my”
2、DispatcherServlet "/"
精确优先原则,没有走spring流程,直接由tomcat处理
扩展:DispatchServlet 如何注册进来
- 容器中自动配置了 DispatcherServlet 属性绑定到 WebMvcProperties;对应的配置文件配置项是 spring.mvc。
- 通过 ServletRegistrationBean<DispatcherServlet> 把 DispatcherServlet 配置进来。
- 默认映射的是 / 路径。

Tomcat处理原生多个Servlet时;
多个Servlet都能处理到同一层路径,精确优选原则
A: /my/
B: /my/1

浙公网安备 33010602011771号