7.1 使用Servlet API
推荐使用以下方式
//在主配置类中,使用注解指定扫描Servlet的包,指定原生Servlet组件都放在那里
@ServletComponentScan(basePackages = "com.igeek")
//在自定义的Servlet中,需要继承HttpServlet,并基于Servlet3.0后支持使用的注解标识
@WebServlet(urlPatterns = "/my") //效果:直接响应,没有经过Spring的拦截器
//自定义的过滤器
@WebFilter(urlPatterns={"/css/*","/images/*"})
//自定义的监听器
@WebListener
7.2 使用RegistrationBean
ServletRegistrationBean
, FilterRegistrationBean
, and ServletListenerRegistrationBean
@Configuration
public class MyRegistConfig {
@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());
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
return filterRegistrationBean;
}
@Bean
public ServletListenerRegistrationBean myListener(){
MySwervletContextListener mySwervletContextListener = new MySwervletContextListener();
return new ServletListenerRegistrationBean(mySwervletContextListener);
}
}
7.3 【源码分析】DispatcherServlet 如何注册
扩展:DispatchServlet 如何注册进来?
- 容器中自动配置了 DispatcherServlet 属性绑定到 WebMvcProperties;对应的配置文件配置项是 spring.mvc。
- 通过 ServletRegistrationBean<DispatcherServlet> 把 DispatcherServlet 配置进来。
- 默认映射的是 / 路径。
Tomcat-Servlet处理原则:
多个Servlet都能处理到同一层路径时,会精确优选原则,去匹配执行。