servlet原生组件servlet、listener、filter
自定义servlet
- 方式一
首先实现HttpServlet接口,使用@WebServlet注解声明映射
@WebServlet(urlPatterns = "/*")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("MyServlet");
}
}
使用注解扫描添加Servlet
@SpringBootApplication
@ServletComponentScan(basePackages = "com.szm.servlet")
public class SpringbootApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(SpringbootApplication.class, args);
}
}
- 方式二
使用ServletRegistrationBean添加
@Configuration
public class MyServletConfiguration {
@Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new MyServlet(), "/*");
}
}
自定义filter
- 方式一
使用@WebFilter注解,一定要使用@ServletComponentScan扫描到filter,或者加上@Component注解,单独的@WebFilter是不会生效的
@WebFilter(urlPatterns = "/*")
public class TestFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("TestFilter");
filterChain.doFilter(servletRequest,servletResponse);
}
}
- 方式二
使用FilterRegistrationBean添加
@Configuration
public class MyServletConfiguration {
@Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new MyServlet(), "/*");
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
// FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new TestFilter(), servletRegistrationBean());
// return filterRegistrationBean;
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new TestFilter());
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
自定义listener
- 方式一
使用@WebListener,一定要使用@ServletComponentScan扫描到listener,或者使用@Component声明listener类
@WebListener
public class TestListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("TestListener");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
- 方式二
使用ServletListenerRegistrationBean添加
@Configuration
public class MyServletConfiguration {
@Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new MyServlet(), "/*");
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new TestFilter(), servletRegistrationBean());
return filterRegistrationBean;
}
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean(){
return new ServletListenerRegistrationBean(new MyListener());
}
}