0%

springboot注册servlet

springboot注册servlet

有时候在springboot中依然需要注册servlet,filter,listener,就以servlet为例来进行说明,另外两个也都类似

使用@WebServlet注解

在servlet3.0之后,servlet注册支持注解注册,而不需要在web.xml中进行配置,类似的,对于Filter使用@WebFilter注解,对于Listener使用@WebListener注解

1
2
3
4
5
6
7
8
9
10
11
12
13
@WebServlet(name = "helloWorldServlet",urlPatterns = "/helloWorldServlet",
initParams = {
@WebInitParam(name = "name",value = "张三")
})
public class HelloWorldServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = getServletConfig().getInitParameter("name");
System.out.println("helloWorldServlet ---- doPost");
resp.getOutputStream().println(name);
}
}

使用ServletRegistrationBean

springboot为注册servlet专门提供了一个bean,可以使用该bean进行注册,类似的对于Filter提供了FilterRegistrationBean,对于Listener提供了ServletListenerRegistrationBean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Configuration
public class ServletRegistConfig {

@Bean
public ServletRegistrationBean registServlet(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
// servlet
servletRegistrationBean.setServlet(new RegistServlet());
List<String> urlMappings = new ArrayList<>();
urlMappings.add("/registServlet");
// 地址映射
servletRegistrationBean.setUrlMappings(urlMappings);
// servlet名称
servletRegistrationBean.setName("registServlet");

Map<String,String> initMap = new HashMap<>();
initMap.put("name","李四");
// servlet的初始参数
servletRegistrationBean.setInitParameters(initMap);

return servletRegistrationBean;

}
}

动态注册

springboot中还提供了动态注册的方式,需要实现ServletContextInitializer接口

1
2
3
4
5
6
7
8
9
10
11
@Component
public class ServletRegistConfiguration implements ServletContextInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
ServletRegistration.Dynamic dynamic = servletContext.addServlet("registServlet", RegistServlet.class);
// 地址映射
dynamic.addMapping("/regist");
// servlet的初始参数
dynamic.setInitParameter("name","王五");
}
}

欢迎关注我的其它发布渠道