springboot注入servlet的方法
问:有了springMVC,为什么还要用servlet?有了servlet3的注解,为什么还要使用ServletRegistrationBean注入的方式?
使用场景:在有些场景下,比如我们要使用hystrix-dashboard,这时候就需要注入HystrixMetricsStreamServlet(第三方的servlet),该servlet是hystrix的组件。
一、代码
1、TestServlet(第一个servlet)
packagecom.xxx.secondboot.servlet; importjava.io.IOException; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; publicclassTestServletextendsHttpServlet{ privatestaticfinallongserialVersionUID=-4619665430596950563L; @Override protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{ System.out.println("zhaojigangservlet"); } @Override protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{ this.doGet(req,resp); } }
2、Testservlet2(第二个servlet)
packagecom.xxx.secondboot.servlet; importjava.io.IOException; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; publicclassTestServlet2extendsHttpServlet{ privatestaticfinallongserialVersionUID=3788279972938793265L; @Override protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{ System.out.println("zhaojigangservlet2"); } @Override protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{ this.doGet(req,resp); } }
3、ServletConfig(servlet注入配置类)
packagecom.xxx.secondboot.servlet; importorg.springframework.boot.context.embedded.ServletRegistrationBean; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; @Configuration publicclassServletConfig{ @Bean publicTestServlettestServlet(){ returnnewTestServlet(); } @Bean publicServletRegistrationBeantestServletRegistrationBean(TestServlettestServlet){ ServletRegistrationBeanregistration=newServletRegistrationBean(testServlet); registration.setEnabled(true); registration.addUrlMappings("/servlet/test"); returnregistration; } /********************************************/ @Bean publicTestServlet2testServlet2(){ returnnewTestServlet2(); } @Bean publicServletRegistrationBeantest2ServletRegistrationBean(TestServlet2testServlet2){ ServletRegistrationBeanregistration=newServletRegistrationBean(testServlet2); registration.setEnabled(true); registration.addUrlMappings("/servlet/test2"); returnregistration; } }
说明:使用ServletRegistrationBean来注入servlet,对于每一个servlet都有一个ServletRegistrationBean来注入。
注意:如果只是自己要使用servlet,可以直接只用servlet3的注解来声明servlet就好,但是像HystrixMetricsStreamServlet这样的第三方servlet,就只能通过上边这样的方式来搞了。
二、测试
启动服务,浏览器输入"http://localhost:8083/servlet/test","http://localhost:8083/servlet/test2",查看console的输出。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。