您可以使用实现ServletContextListener的WebListener。
所以在部署中,您可以读取系统属性并将它们设置为属性。
单独或在地图中。
system.properties:
比方说你有一个文件system.properties
的内容:
buildType=myType
systemVersion=v55
WebListener:
的WebListener可能是这样的:
package testingThings.properties;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class ContextListener implements ServletContextListener {
public ContextListener() {}
public void contextDestroyed(ServletContextEvent sce) {}
public void contextInitialized(ServletContextEvent sce) {
InputStream stream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("testingThings/properties/system.properties");
Properties props = new Properties();
try {
props.load(stream);
} catch (IOException e) {
e.printStackTrace();
}
HashMap<String, String> map = new HashMap<String, String>();
for (final String name : props.stringPropertyNames()) {
map.put(name, props.getProperty(name));
}
sce.getServletContext().setAttribute("system", map);
}
}
JSP:
在JSP中,你可以通过system
属性这样的循环:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head><title>access map of system properties</title></head>
<body>
<h3>access map of system properties</h3>
<table>
<c:forEach items="${system}" var="property">
<tr>
<td>${property.key}:</td>
<td>${property.value}</td>
</tr>
</c:forEach>
<tr>
</table>
<h3>directly access of map properties</h3>
<table>
<tr>
<td>buildType:</td>
<td>${system.buildType}</td>
</tr>
<tr>
<td>systemVersion:</td>
<td>${system.systemVersion}</td>
</tr>
<tr>
</table>
</body>
如果系统性能是动态变化的,
您可以更新它们,直接在上下文属性(与system.properties文件并行)
那么一个JSP *就是一个各种各样的servlet。但是由于它是由声明性标记构成的,并为其添加不重要的代码语句是一种惯例,所以您确实可以添加一个集中式(无状态)服务,以便以servlet的形式从所有JSP中检索该信息可以访问。但是我个人无法看到servlet过滤器如何在这个范围内被限制。 – Mena
另一种选择是创建一个PropertiesTag - 然后可以在JSP中包含该属性标记以呈现服务器属性。 – donlys
@donlys - 你能详细说明吗? –