SpringBoot注册Servlet的三种方式
所属分类 springboot
浏览量 891
ServletRegistrationBean 注册
Servlet组件扫描
ServletContextInitializer 动态注册
SpringBoot 提供ServletRegistrationBean, FilterRegistrationBean, ServletListenerRegistrationBean
分别注册 Servlet, Filter, Listener
@Bean
public ServletRegistrationBean registerHelloServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new HelloServlet(), "/hello");
servletRegistrationBean.addInitParameter("name", "dyyx");
return servletRegistrationBean;
}
Servlet3.0 之前,Servlet Filter Listener 在 web.xml 中配置
Servlet3.0之后 可基于代码或注解配置
@WebServlet
@WebFilter
@WebListener
@WebServlet(name = "helloServlet2", urlPatterns = "/hello2", asyncSupported = true,
initParams = {@WebInitParam(name = "name", value = "dyyx"),})
public class HelloServlet2 extends HttpServlet {
注意!!!
使用内嵌容器 ,需要开启 Servlet 组件扫描 @ServletComponentScan
@SpringBootApplication
@ServletComponentScan
public class App {
org.springframework.boot.web.servlet.ServletContextInitializer
@Component
public class ServletInitBean implements ServletContextInitializer{
@Override
public void onStartup(ServletContext servletContext) {
ServletRegistration initServlet = servletContext
.addServlet("helloServlet3", HelloServlet3.class);
initServlet.addMapping("/hello3");
initServlet.setInitParameter("name", "dyyx");
}
}
完整代码
https://gitee.com/dyyx/demos/tree/master/springboot_servlet
上一篇
下一篇
springboot读取配置的几种方式
feign ribbon 独立使用例子
springcloud zuul 简介
springboot获取内置tomcat端口
关于流计算的若干想法
SpringBoot admin 简介