在javaWeb项目中,一些常用的数据可以放到.properties文件中,以便于修改和维护。
我需要实现的是将.properties文件的配置信息显示在.jsp中,用于前端展示。
目前我只知道有这两种方法可以实现
1、使用ResourceBundle
2、使用 JSTL 标签 fmt:message
准备
- 首先需要创建一个 .properties 文件
- 自己创建的配置文件和工程中的配置文件一样放在
resources
目录下 - 创建的配置文件为 conf-my.properties
- 配置文件具体内容如下
name=阿豪
version=1.0
1、使用ResourceBundle
- 在jsp页面引入 ResourceBundle
<%@ page language="java" import="java.util.ResourceBundle" %>
- 使用ResourceBundle 加载properties文件
ResourceBundle resource = ResourceBundle.getBundle("conf-my"); //不需要后缀
- 读取配置值
resource.getString("version"); //properties中的key
具体示例
<%@ page language="java" import="java.util.ResourceBundle" %>
<%
ResourceBundle resource = ResourceBundle.getBundle("conf-my"); //不需要后缀
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- 通过resource.getString(key) 获取value -->
<title><%=resource.getString("name") %></title>
</head>
<body>
<p>version:<%=resource.getString("version") %></p>
<script type="text/javascript">
//js 使用方式
var version= 'resource.getString("version")';
</script>
</body>
</html>
2、使用JSTL标签fmt:message
- 引入jstl中的fmt标签
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
- 使用fmt:setBundle加载properties文件(basename:为文件名,var:变量名)
<fmt:setBundle basename="conf-my" var="conf-my" />
- 使用fmt:message读取配置值(key配置文件的key,var:变量名,bundle引用配置文件)
<fmt:message key="varsion" var="v" bundle="${conf-my}" />
- 使用EL表达式读取配置值
${v}
具体示例
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!-- 加载systemInfo配置文件 -->
<fmt:setBundle basename="conf-my" var="conf-my" />
<!-- 读取配置值varsion -->
<fmt:message key="varsion" var="v" bundle="${conf-my}" />
<fmt:message key="name" var="name" bundle="${conf-my}" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- 直接输出配置值 -->
<title>${name}</title>
</head>
<body>
<p>version:${v} %></p>
<script type="text/javascript">
//js 使用方式
var version= 'resource.getString("version")';
</script>
</body>
</html>
乱码问题
有的人读取 properties 文件中的中文会出现乱码的情况,我就是其中的一个
在百度也找了一些解决方案,但是大部分都是在后台处理的,而我不想这么麻烦,我只需要读取一个配置就可以了。
最终我找到了一个简单的解决方案
1、将 .properties 配置文件中的中文转换为Unicode
\u963f\u8c6a
,转换后大概是这样
name=阿豪
version=1.0
修改为
name=\u963f\u8c6a
version=1.0
就可以正常显示了。
2、如果你使用的IDEA开发工具不妨试试这种方法
- 在文件创建的时候可能编码格式不是utf-8;
- 你需要在你的IDEA中设置一下
- Ctrl + Alt + s 打开设置
- 如果还是无效,将.properties文件删除重新创建即可