四种做用域:java
Web应用中的变量存放在不一样的jsp对象中,会有不同的做用域,四种不一样的做用域排序是 pageContext < request < session < application;web
一、pageContext:页面域,仅当前页面有效,离开页面后,不论重定向仍是转向(即不管是redirect仍是forward),pageContext的属性值都失效;浏览器
二、request:请求域,在一次请求中有效,若是用forward转向,则下一次请求还能够保留上一次request中的属性值,而redirect重定向跳转到另外一个页面则会使上一次request中的属性值失效;session
三、session:会话域,在一次会话过程当中(从浏览器打开到浏览器关闭这个过程),session对象的属性值都保持有效,在此次会话过程,session中的值能够在任何页面获取;app
四、application:应用域,只要应用不关闭,该对象中的属性值一直有效,而且为全部会话所共享。jsp
利用ServletContextListener监听器,一旦应用加载,就将properties的值存储到application当中ide
如今须要在全部的jsp中都能经过EL表达式读取到properties中的属性,而且是针对全部的会话,故这里利用application做用域,spa
那么何时将properties中的属性存储到application呢?由于是将properties的属性值做为全局的变量以方便任何一次EL的获取,因此在web应用加载的时候就将值存储到application当中,code
这里就要利用ServletContextListener:xml
ServletContextListener是Servlet API 中的一个接口,它可以监听 ServletContext 对象的生命周期,实际上就是监听 Web 应用的生命周期。
当Servlet 容器启动或终止Web 应用时,会触发ServletContextEvent 事件,该事件由ServletContextListener 来处理。
具体步骤以下:
一、新建一个类PropertyListenter实现 ServletContextListener接口的contextInitialized方法;
二、读取properties配置文件,转存到Map当中;
三、使用ServletContext对象将Map存储到application做用域中;
/** * 设值全局变量 * @author meikai * @version 2017年10月23日 下午2:15:19 */ public class PropertyListenter implements ServletContextListener { /* (non-Javadoc) * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) */ @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ @Override public void contextInitialized(ServletContextEvent sce) { /** * 读取properties文件 * */ final Logger logger = (Logger) LoggerFactory.getLogger(PropertyListenter.class); Properties properties = new Properties(); InputStream in = null; try { //经过类加载器进行获取properties文件流 in = PropertiesUtil.class.getClassLoader().getResourceAsStream("kenhome-common.properties"); properties.load(in); } catch (FileNotFoundException e) { logger.error("未找到properties文件"); } catch (IOException e) { logger.error("发生IOException异常"); } finally { try { if(null != in) { in.close(); } } catch (IOException e) { logger.error("properties文件流关闭出现异常"); } } /** * 将properties文件转存到map */ Map<String, String> pros = new HashMap<String,String>((Map)properties); /** * 将Map经过ServletContext存储到全局做用域中 */ ServletContext sct=sce.getServletContext(); sct.setAttribute("pros", pros); } }
4、在web.xml中配置上面的的监听器PropertyListenter:
<!-- 全局变量监听器,读取properties文件,设值为全局变量 --> <listener> <listener-class>com.meikai.listener.PropertyListenter</listener-class> </listener>
配置好后,运行Web应用,就能在全部的jsp页面中用EL表达式获取到properties中的属性值了。