spring boot(18)-servlet、filter、listener

来源:互联网 发布:网络借贷暂行管理办法 编辑:程序博客网 时间:2024/06/05 12:04

servlet、filter、listener的用法就不讲了,只讲如何在spring boot中配置它们。有两种方式,一种是从servlet3开始提供的注解方式,另一种是spring的注入方式

servlet注解方式

servlet3.0以前,servlet、filter、listener需要在web.xml中配置,从servlet3.0开始,支持通过类注解进行配置。在spring boot中如果要支持这种注解,必须在配置类增加一个@ServletComponentScan注解,来扫描servlet的注解
@ServletComponentScan@SpringBootApplication

servlet注解配置,urlPatterns就是这个servlet的请求路径,相当于spring mvc的mapping

@WebServlet(urlPatterns = "/hello")public class MyServlet extends HttpServlet {
filter注解配置,urlPatterns就是这个过滤器要过滤哪些路径
@WebFilter(urlPatterns = "/*")public class MyFilter implements Filter {
listener注解配置,监听器都是全局性的,不需要配置路径
@WebListenerpublic class MyListener implements ServletContextListener {

spring的注入方式

//servlet@Beanpublic ServletRegistrationBean myServlet() {//配置servlet及其请求路径return new ServletRegistrationBean(new MyServlet(), "/hello");}//过滤器@Beanpublic FilterRegistrationBean myFilter() {FilterRegistrationBean myFilter =new FilterRegistrationBean();//配置过滤器myFilter.setFilter(new MyFilter());//配置过滤路径myFilter.addUrlPatterns("/*");return myFilter;}//监听器@Beanpublic ServletListenerRegistrationBean<MyListener> myListener() {return new ServletListenerRegistrationBean<MyListener>(new MyListener());}

id命名冲突

上面的spring注入方法我都是用my*来命名,在第二篇中我讲过,这个方法名就是在spring中注册的bean的id。有一种习惯就是用类名的首字母小写来命名id,如下
@Beanpublic ServletRegistrationBean servletRegistrationBean() {
如果你的项目中配置了我在11篇讲的druid监控,这个方法名id已经被druid使用了,这个配置也将无法生效。这就是不使用spring boot默认组件可能会引发的一些冲突问题,所以如非必要,建议优先使用spring boot默认的各种组件,稳定性兼容性更高。

servlet注解还是spring注入

servlet注解不会有上面的冲突问题,而且简单易用。更主要的是,servlet是出自java官方的web技术,如tomcat之类的服务器,只知道有servlet,而不知道spring为何物。所有对spring mvc控制层的请求,都是通过一个servlet也就是DispatchServlet进行分发的。请求首先到达servlet,分发以后才会到spring,如果不分发也就没spring什么事了。spring需要依赖servlet才能处理请求,将你所依赖的东西整合到你自己的框架内部,是不是有点本末倒置?所以,使用servlet注解才是原味的servlet


阅读全文
0 0