SpringBoot使用Servlet、Filter、Listener三大组件
SpringBoot使用Servlet、Filter、Listener三大组件
在SpringBoot中我们如何使用Servlet、Filter、Listener三大组件呢,下面我们看一看
一、Servlet
首先我们需要编写一个自定义Servlet类并继承HttpServlet
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);//doGet方法中调用doPost方法
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("Hello MyServlet");//返回打印出Hello MyServlet
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
然后需要将MyServlet注册到容器中,需要我们在配置类中进行配置
@Bean
public ServletRegistrationBean myServlet(){
//声明一个Servlet注册器对象,传两个参数,一个是我们自己编写的Servlet,另一个就是我们的Servlet要作用的url映射
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet");
return servletRegistrationBean;
}
1
2
3
4
5
6
效果:
二、Filter
首先我们需要编写一个自定义Filter类并实现Filter接口
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("MyFilter process...");
filterChain.doFilter(servletRequest, servletResponse);//放行
}
@Override
public void destroy() {
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
然后需要将MyFilter注册到容器中,需要我们在配置类中进行配置
@Bean
public FilterRegistrationBean myFilter(){
//声明一个Filter注册器对象
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());//注册自定义Filter
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));//设置要作用的url
return registrationBean;
}
1
2
3
4
5
6
7
8
效果:
三、Listener
首先我们需要编写一个自定义MyListener类并实现ServletContextListener接口
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项目销毁");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
然后需要将MyListener注册到容器中,需要我们在配置类中进行配置
@Bean
public ServletListenerRegistrationBean myListener(){
//声明一个Listener注册器对象,注册MyListener
ServletListenerRegistrationBean registrationBean = new ServletListenerRegistrationBean(new MyListener());
return registrationBean;
}
1
2
3
4
5
6
效果:
大家可以动手敲一敲,试一试!
————————————————
版权声明:本文为CSDN博主「ITMANLZY」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_45345374/article/details/114699215