之前从Java web一路学习过来,一直没有学习过Servlet容器类的一些高级用法,因为学完简单的JSP以及Servlet编写之后就开始了Spring的学习
对web应用的一些常用变量进行 application 也就是应用开启的生存周期做静态化处理
<listener>
<listener-class>xyz.springabc.web.listener.StartUpListener</listener-class>
</listener>
首先添加Listen,一个观察者
public class StartUpListener implements ServletContextListener {//这个观察者实现了 ServletContextListener /**
* Default constructor.
*/
public StartUpListener() {
// TODO Auto-generated constructor stub
} /**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
} /**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent event) {//Servlet上下文初始化的时候调用这个函数
ServletContext application = event.getServletContext();//得到上下文
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(application);//利用spring的工具类得到Spring上下文
PropertyServ propertyServ = applicationContext.getBean(PropertyServ.class);//用spring上下文得到Service bean
propertyServ.setup(application);//把设置信息都扔到里面,页面可以直接读取
}}
下面是Service的一些实现
@Service
public class PropertyServ { @Autowired
private PropertyRepo propertyRepo; @Autowired
private FieldRepo fieldRepo; private ServletContext application; /**
* 启动监听设置这个属性
* @param application
*/
public void setup(ServletContext application){//调用了setup方法
this.application=application;
for(Property property:propertyRepo.findAll()){
Field field = fieldRepo.findOneByProperty(property); application.setAttribute(property.getKeyword(), field);//这里从dao层读出 key value 全部加载到application对象里面去,这样在JSP页面可以直接取得这些常量值 而不用去调用Service每次从数据库获得这些网站静态变量
}
}}