这篇文章主要介绍servlet等容器对象的自定义配置。 spring-boot的强大之处就是做到了各种扩展使用都是插拔式的,方便我们专注业务方法的编写,简化环境的搭建。
按照官方给定的方式
![微信截图_20161225142839.png 微信截图_20161225142839.png](http://image109.360doc.com/DownloadImg/2018/01/1217/121694177_1_20180112060939830.png) 这些都是servlet3的注解配置。
下面开始介绍下如何在spring-boot的基础上启用servlet的容器对象的配置。 案例代码在 “spring-boot(六)缓存配置” 的基础上改造
项目结构图
![微信截图_20161225143209.png 微信截图_20161225143209.png](http://image109.360doc.com/DownloadImg/2018/01/1217/121694177_2_20180112060939955.png)
1。 新建文件夹 web/filter 创建 MyFilter.java
@WebFilter(filterName="myFilter",urlPatterns="/*") public class MyFilter implements Filter { private Logger log = LoggerFactory.getLogger(this.getClass());
@Override public void destroy() { log.info("MyFilter.destroy()..."); }
@Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { log.info("MyFilter.doFilter()..."); arg2.doFilter(arg0, arg1); }
@Override public void init(FilterConfig arg0) throws ServletException { log.info("MyFilter.init()..."); }
}
创建 MyListener.java
@WebListener public class MyListener implements ServletContextListener { private Logger log = LoggerFactory.getLogger(this.getClass());
@Override public void contextDestroyed(ServletContextEvent arg0) { log.info("MyListener.contextDestroyed()..."); }
@Override public void contextInitialized(ServletContextEvent arg0) { log.info("MyListener.contextInitialized()..."); }
}
- 在主启动类上加入
@ServletComponentScan 启用servlet组件的扫描
@ServletComponentScan @EnableCaching @SpringBootApplication public class MainApplication {
public static void main(String[] args) throws Exception { SpringApplication.run(MainApplication.class, args); }
}
到此为止,servlet的启用已经完成,启动主启动类
![微信截图_20161225143932.png 微信截图_20161225143932.png](http://image109.360doc.com/DownloadImg/2018/01/1217/121694177_3_2018011206094017.png)
浏览器访问 http://localhost:666/hello/list
![微信截图_20161225144001.png 微信截图_20161225144001.png](http://image109.360doc.com/DownloadImg/2018/01/1217/121694177_4_20180112061040220.png)
其实到这里已经可以了,但是以上部分毕竟只是启用了,但是如何和页面交互传值,我还是举个例子来说明下。 比如如何将MyConfig的值保存在application中,页面如何获取application中的值 ?
扩展 MyListener.java 代码
@WebListener public class MyListener implements ServletContextListener { private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired MyConfig config;
@Override public void contextDestroyed(ServletContextEvent arg0) { log.info("MyListener.contextDestroyed()..."); }
@Override public void contextInitialized(ServletContextEvent arg0) { log.info("MyListener.contextInitialized()..."); arg0.getServletContext().setAttribute("config", config); }
}
在 /templates/list.html 文件中增加config的输出
<div th:text="${application.config.info}"></div>
浏览器再次访问 http://localhost:666/hello/list
![微信截图_20161225145737.png 微信截图_20161225145737.png](http://image109.360doc.com/DownloadImg/2018/01/1217/121694177_5_20180112061140345.png)
|