springboot 注册三大组件(servlet,Filter,Listener)
注册servlet
创建一个自定义servlet
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getOutputStream().println("hahaha");
}
}
在配置类中注册servlet
@Configuration
public class MyMvcConfig {
@Bean
public ServletRegistrationBean addservlet()
{ // 创建Servlet注册Bean
ServletRegistrationBean<MyServlet> servletServletRegistrationBean=new ServletRegistrationBean<MyServlet>();
// 注册Servlet
servletServletRegistrationBean.setServlet(new MyServlet());
// 设置Servlet名称
servletServletRegistrationBean.setName("second_servlet");
// 设置Servlet访问地址
servletServletRegistrationBean.addUrlMappings("/hello");
// 设置加载参数
servletServletRegistrationBean.setLoadOnStartup(1);
return servletServletRegistrationBean;
}
注册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("qwer");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() { }
}
配置类注册Filter
@Bean
public FilterRegistrationBean addFilter()
{
FilterRegistrationBean<MyFilter> filterFilterRegistrationBean=new FilterRegistrationBean<>();
filterFilterRegistrationBean.setFilter(new MyFilter());
//拦截的请求
filterFilterRegistrationBean.setUrlPatterns(Arrays.asList("/haha"));
return filterFilterRegistrationBean;
}
注册Listener
创建一个自定义Listener
public class MyListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("项目销毁");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("项目创建");
}
}
配置类注册Listener
@Bean
public ServletListenerRegistrationBean addListener()
{
ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBean=new ServletListenerRegistrationBean<>();
servletListenerRegistrationBean.setListener(new MyListener());
return servletListenerRegistrationBean;
}