Java web 应用全局变量_将properties文件的配置设置为整个Web应用的全局变量。

本文介绍了如何在Java Web应用中设置全局变量,通过ServletContextListener监听器在应用启动时读取properties文件并存储到application作用域,使得所有会话都能访问这些配置属性。详细步骤包括创建监听器类、读取配置文件、将属性存入application以及web.xml的配置。
摘要由CSDN通过智能技术生成

四种作用域:

Web应用中的变量存放在不同的jsp对象中,会有不一样的作用域,四种不同的作用域排序是pageContext < request < session < application;

1、pageContext:页面域,仅当前页面有效,离开页面后,不论重定向还是转向(即无论是redirect还是forward),pageContext的属性值都失效;

2、request:请求域,在一次请求中有效,如果用forward转向,则下一次请求还可以保留上一次request中的属性值,而redirect重定向跳转到另一个页面则会使上一次request中的属性值失效;

3、session:会话域,在一次会话过程中(从浏览器打开到浏览器关闭这个过程),session对象的属性值都保持有效,在这次会话过程,session中的值可以在任何页面获取;

4、application:应用域,只要应用不关闭,该对象中的属性值一直有效,并且为所有会话所共享。

利用ServletContextListener监听器,一旦应用加载,就将properties的值存储到application当中

现在需要在所有的jsp中都能通过EL表达式读取到properties中的属性,并且是针对所有的会话,故这里利用application作用域,

那么什么时候将properties中的属性存储到application呢?因为是将properties的属性值作为全局的变量以方便任何一次EL的获取,所以在web应用加载的时候就将值存储到application当中,

这里就要利用ServletContextListener:

ServletContextListener是Servlet API 中的一个接口,它能够监听 ServletContext 对象的生命周期,实际上就是监听 Web 应用的生命周期。

当Servlet 容器启动或终止Web 应用时,会触发ServletContextEvent事件,该事件由ServletContextListener 来处理。

具体步骤如下:

1、新建一个类PropertyListenter实现 ServletContextListener接口的contextInitialized方法;

2、读取properties配置文件,转存到Map当中;

3、使用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 pros = new HashMap((Map)properties);

/**

* 将Map通过ServletContext存储到全局作用域中

*/

ServletContext sct=sce.getServletContext();

sct.setAttribute("pros", pros);

}

}

4、在web.xml中配置上面的的监听器PropertyListenter:

com.meikai.listener.PropertyListenter

配置好后,运行Web应用,就能在所有的jsp页面中用EL表达式获取到properties中的属性值了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值