Spring Boot 注册 Servlet 三大组件

摘要
三大组件包括 Servlet、Filter、Listener
由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,所以没有web.xml文件。

三大组件的注册

这个注册都是在自定义的配置类里面注册(即有@Configraution的类里)

ServletRegistrationBean

P.s. 这里自定义的Servlet继承HttpServlet

1
2
3
4
5
6
//注册三大组件
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
return registrationBean;
}

自定义Servlet代码

1
2
3
4
5
6
7
8
9
10
11
12
13
public class MyServlet extends HttpServlet {

//处理get请求
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("Hello MyServlet");
}
}

FilterRegistrationBean

P.s. 自定义的过滤器实现Filter

1
2
3
4
5
6
7
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
return registrationBean;
}

自定义过滤器代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MyFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("MyFilter process...");
chain.doFilter(request,response);
}

@Override
public void destroy() {
}
}

ServletListenerRegistrationBean

P.s. 自定义监听器 实现ServletContextListener

1
2
3
4
5
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}

自定义监听器代码

1
2
3
4
5
6
7
8
9
10
11
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitialized...web应用启动");
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("contextDestroyed...当前web项目销毁");
}
}