Web原生组件指的是:Servlet、Filter、Listener
@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("servlet");
}
}
main方法加上@ServletComponentScan
@ServletComponentScan
@SpringBootApplication
public class Boot2MyApplication {
public static void main(String[] args) {
SpringApplication.run(Boot2MyApplication.class, args);
}
}
官方文档也是这样说明的:
测试filter:
@Slf4j
@WebFilter(urlPatterns = "/myServlet")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("init");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
log.info("MyFilter doFilter");
chain.doFilter(request, response);
}
@Override
public void destroy() {
log.info("destroy");
}
}
官方文档上上面还写了一个方式:
测试:先注释掉filter和servlet上面的注解
编写配置类:
@Configuration
public class MyRegistryConfig {
@Bean
public ServletRegistrationBean<MyServlet> myServlet(){
MyServlet myServlet = new MyServlet();
return new ServletRegistrationBean<>(myServlet, "/myServlet");
}
@Bean
public FilterRegistrationBean<MyFilter> myFilterFilterRegistrationBean(){
MyFilter myFilter = new MyFilter();
return new FilterRegistrationBean<>(myFilter,myServlet());
}
}
测试,仍然成功。Listener与其类似,使用的是ServletListenerRegistrationBean
注册,这里不再演示。
进入DispatcherServletAutoConfiguration
自动配置类:有一个内部类DispatcherServletConfiguration
这里向容器中注入了一个DispatcherServlet,DispatcherServlet默认处理的请求路径是“/”
后面又有一个DispatcherServletRegistrationConfiguration
,向容器中注册了DispatcherServletRegistrationBean
,并设置了DispatcherServlet
而DispatcherServletRegistrationBean
是继承于ServletRegistrationBean
在tomcat中,Servlet处理请求为精确优先处理原则。
如果有两个servlet,AServlet可以处理"/",BServlet可以处理“/hello”,那么如果发送“/hello”请求,则为BServlet处理,因为BServlet比AServlet精确。
原文:https://www.cnblogs.com/wwjj4811/p/14643899.html