SpringBoot要注入Servlet组件有两种方法:原生的ServletAPI 和 Spring注解方法
Servlet:Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。
Filter:Filter也称过滤器,它是Servlet技术中最实用的技术,Web开发人员通过Filter技术,对web服务器管理的所有web资源。
Listener:监听某个事件的发生,状态的改变。
原生ServletAPI
1. main方法
@ServletComponentScan(basePackages = "com.example") //加入这个注解可以扫描Servlet组件 @SpringBootApplication public class MainApplication { public static void main(String[] args) { SpringApplication.run(MainApplication.class,args); } }
2. Servlet
@WebServlet(urlPatterns = "/my") //加上这个注解才能被扫描到,处理 "/my" 这个请求 public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("666666"); } }
3. Filter
@Slf4j @WebFilter(urlPatterns = {"/css/*","/images/*"}) //指定拦截的路径 public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { log.info("MyFilter初始化完成"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { log.info("MyFilter工作"); } @Override public void destroy() { log.info("MyFilter销毁"); } }
4. Listener
@Slf4j @WebListener public class MyListener implements ServletContextListener { //Listener有很多种,这里以ContextListener为例 @Override public void contextInitialized(ServletContextEvent sce) { log.info("监听到项目初始化完成"); } @Override public void contextDestroyed(ServletContextEvent sce) { log.info("监听到项目销毁"); } }
用Config类注册(不用再写@WebListener等注解)
@Configuration(proxyBeanMethods = true) //保证依赖的组件始终是单实例
public class MyRegistConfig {
@Bean //注册成组件
public ServletRegistrationBean Servlet(){ //返回一个 ServletRegistrationBean
MyServlet myServlet = new MyServlet(); //MyServlet类还是要自己写的
return new ServletRegistrationBean(myServlet,"/my","/my02"); //后面表示对应的请求路径
}
@Bean
public FilterRegistrationBean Filter(){
MyFilter myFilter = new MyFilter();
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
//return new FilterRegistrationBean(myFilter,Servlet()); //也可以直接用Servlet() 这个注册方法来提取拦截路径
return filterRegistrationBean;
}
@Bean
public ServletListenerRegistrationBean Listener(){
MyListener myListener = new MyListener();
return new ServletListenerRegistrationBean(myListener);
}
}