注册Servlet三大组件
简介
Servlet三大组件Servlet、Filter、Listener我们听说的比较多,在springboot当中也可以添加这三大组件,使用起来也比较方便
讲解
编写三大组件
添加三大组件之前我们需要先编写三大组件
MyServlet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class MyServlet extends HttpServlet {
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("MyServlet 被调用"); resp.getWriter().write("Hello MyServlet"); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("MyServlet 被调用"); resp.getWriter().write("Hello MyServlet"); } }
|
MyFilter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| 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 被调用"); chain.doFilter(request,response);
}
@Override public void destroy() {
} }
|
MyListener:
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项目销毁"); } }
|
进行相应的配置
servlet要添加进容器需要以ServletRegistrationBean的形式,fliter要添加进容器需要以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 25 26 27 28 29 30 31 32 33
|
@Configuration public class MyServerConfig {
@Bean public ServletRegistrationBean myServlet(){ ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet"); registrationBean.setLoadOnStartup(1); return registrationBean; }
@Bean public FilterRegistrationBean myFilter(){ FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new MyFilter()); registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet")); return registrationBean; }
@Bean public ServletListenerRegistrationBean myListener(){ ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener()); return registrationBean; }
}
|
最终效果
访问http://localhost:8080/hello和http://localhost:8080/myServlet

总结
springboot继续学习当中