在jsp页面中直接读取.properties文件中的配置

来源:互联网 发布:sql删除 编辑:程序博客网 时间:2024/06/05 06:45

在JavaWeb项目中可以将一些通用的配置(如产品名称等)放置在.properties文件中,然后在页面中直接读取配置值,在需要对通用配置做变更时即可做到一处修改、处处生效。

前提

  • .properties配置文件放在web-inf/classes文件夹下,即与class文件放在一起
  • 假设有一systemInfo.properties文件,内容如下:
AppName=这是可自定义的产品名称

一、使用ResourceBundle

众所周知,在jsp页面中是可以写java代码的,因此使用java.util包下的ResourceBundle来读取properties文件中的属性

用法

  • 在jsp页面顶部引入java.util包
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%>
  • 使用ResourceBundle 加载properties文件
ResourceBundle resource = ResourceBundle.getBundle("systemInfo"); // 不带properties扩展名的文件名
  • 读取配置值
resource.getString("AppName"); // 属性名


完整示例

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%><%    ResourceBundle resource = ResourceBundle.getBundle("systemInfo");%><!DOCTYPE html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />        <!-- 直接输出配置值 -->        <title><%=resource.getString("AppName") %></title>    </head>    <body>        <script type="text/javascript">            // 赋值给js变量            var appName = 'resource.getString("AppName")';        </script>    </body></html>


二、使用JSTL标签fmt:message

  • 引入jstl中的fmt标签
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
  • 使用fmt:setBundle加载properties文件
<!-- basename为不带properties扩展名的文件名;var为存储该配置文件的变量名 --><fmt:setBundle basename="systemInfo" var="sysInfo" /> // 
  • 使用fmt:message读取配置值
<!-- key为配置文件中的属性名;var为存储该配置值的变量名;bundle为上一步中存储配置文件的变量名 --><fmt:message key="AppName" var="appName" bundle="${sysInfo}" /> 
  • 使用EL表达式读取配置值
<!-- 上一步中存储配置值的变量名 -->${appName}


完整示例

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%><!-- 加载systemInfo配置文件 --><fmt:setBundle basename="systemInfo" var="sysInfo" /><!-- 读取配置值AppName,并赋值给变量appName --><fmt:message key="AppName" var="appName" bundle="${sysInfo}" /><!DOCTYPE html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />        <!-- 直接输出配置值 -->        <title>${appName}</title>    </head>    <body>        <script type="text/javascript">            // 赋值给js变量            var appName= '${appName}';        </script>    </body></html>
原创粉丝点击