您可以使用實現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 - 你能詳細說明嗎? –