SpringBoot之整合三大基础组件
三大组件其实就是我们常说的 Servlet,Filter,和Listener。下面我们看一下在SpringBoot如何整合这三大组件。
定义三大组件
定义servlet:
1 2 3 4 5 6 7 8
| @WebServlet(urlPatterns = "/iServlet") public class IServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("IServlet"); } }
|
定义Filter:
1 2 3 4 5 6 7 8 9 10
| @WebFilter("/*") public class IFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("iFilter"); filterChain.doFilter(servletRequest,servletResponse); } }
|
定义Listener:
1 2 3 4 5 6 7 8 9 10 11 12 13
| @WebListener public class IRequestListener implements ServletRequestListener {
@Override public void requestInitialized(ServletRequestEvent sre) { System.out.println("requestInitialized"); }
@Override public void requestDestroyed(ServletRequestEvent sre) { System.out.println("requestDestroyed"); } }
|
这里说明一下:Serlvet就其实相当于SpringMvc里面用 @RequestMapping
注解标注了的方法。
应用组件
上面我们已经定义好了三个组件,接下来,我们来看一下如何注册到SpringBoot中去。
1 2 3 4 5 6 7
| @SpringBootApplication @ServletComponentScan(basePackages = "com.hao.springbootservlet.component") public class SpringbootServletApplication { public static void main(String[] args) { SpringApplication.run(SpringbootServletApplication.class, args); } }
|
我们用@ServletComponentScan
去扫描到这三大组件,虽然名字是一servlet开头的,但是可以把这三大组件都扫到。
测试
我们通过浏览器访问localhost:8080/iSerlvet
得到如下结果: