springboot注册Servlet三大组件【Servlet、Filter、Listener】
SpringBoot默认以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,不需要进行xml文件配置。
注册三大组件用以下方式
-
SERVLET
一般情况下显示需要写自己的servlet去继承HttpServlet,重写doPost和doGet方法。
//处理get请求 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } //处理post请求 @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("Hello MyServlet"); }
接下来在配置类中进行注册。
//注册三大组件
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
//启动顺序
registrationBean.setLoadOnStartup(1);
return registrationBean;
}
-
Filter
需要自定义Filter,实现Filter接口 (三个接口)
Init,初始化
doFilter,过滤
destroy,销毁
chain.doFilter,放行请求接下来在配置中及进行注册
FilterRegistrationBean
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
return registrationBean;
}
-
Listener
contextInitialized,初始化方法,Web项目启动
contextDestroyed,销毁方法,Web项目销毁(直接exit时使用)
ServletListenerRegistrationBean
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}
关于三大组件:就是所有的代码几乎是不可变的,需要写的代码很多,并不适合spring。