四大作用域:
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
*/
MapString, String> pros = new HashMapString,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中的屬性值了。
以上這篇將properties文件的配置設置為整個Web應用的全局變量實現方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。