springboot注入servlet的方法
問:有了springMVC,為什么還要用servlet?有了servlet3的注解,為什么還要使用ServletRegistrationBean注入的方式?
使用場景:在有些場景下,比如我們要使用hystrix-dashboard,這時候就需要注入HystrixMetricsStreamServlet(第三方的servlet),該servlet是hystrix的組件。
一、代碼
1、TestServlet(第一個servlet)
package com.xxx.secondboot.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = -4619665430596950563L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("zhaojigang servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
2、Testservlet2(第二個servlet)
package com.xxx.secondboot.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet2 extends HttpServlet {
private static final long serialVersionUID = 3788279972938793265L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("zhaojigang servlet2");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
3、ServletConfig(servlet注入配置類)
package com.xxx.secondboot.servlet;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServletConfig {
@Bean
public TestServlet testServlet(){
return new TestServlet();
}
@Bean
public ServletRegistrationBean testServletRegistrationBean(TestServlet testServlet){
ServletRegistrationBean registration = new ServletRegistrationBean(testServlet);
registration.setEnabled(true);
registration.addUrlMappings("/servlet/test");
return registration;
}
/********************************************/
@Bean
public TestServlet2 testServlet2(){
return new TestServlet2();
}
@Bean
public ServletRegistrationBean test2ServletRegistrationBean(TestServlet2 testServlet2){
ServletRegistrationBean registration = new ServletRegistrationBean(testServlet2);
registration.setEnabled(true);
registration.addUrlMappings("/servlet/test2");
return registration;
}
}
說明:使用ServletRegistrationBean來注入servlet,對于每一個servlet都有一個ServletRegistrationBean來注入。
注意:如果只是自己要使用servlet,可以直接只用servlet3的注解來聲明servlet就好,但是像HystrixMetricsStreamServlet這樣的第三方servlet,就只能通過上邊這樣的方式來搞了。
二、測試
啟動服務,瀏覽器輸入"http://localhost:8083/servlet/test","http://localhost:8083/servlet/test2",查看console的輸出。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

