我会这样做:
- 加载属性(就像你做的那样)
- 填充映射(因为键和值很容易使用 JSP-EL 访问)
- 在页面属性中设置地图(可从 JSP-EL 访问)
- 遍历地图(使用核心 JSTL)
- 使用
key 和value 填充选项标签
像这样:
<%@ page contentType="text/html; charset=UTF-8"
import="java.io.InputStream, java.util.HashMap, java.util.Properties" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
// 1. load the properties
InputStream stream = application.getResourceAsStream("foo.properties");
Properties props = new Properties();
props.load(stream);
// 2. fill a map
HashMap<String, String> linkMap = new HashMap<String, String>();
for (final String name: props.stringPropertyNames()) {
linkMap.put(name, props.getProperty(name));
}
// 3. set the map in a page attribute
pageContext.setAttribute("linkMap", linkMap);
%>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h3>select field with map</h3>
<select name="link">
<!-- 4. iterate through the map -->
<c:forEach items="${linkMap}" var="link">
<!-- 5. populate the option tags -->
<option value="${link.key}">${link.value}</option>
</c:forEach>
</select>
</body>
在 JSP 中使用 scriptlet 是不好的做法。
您应该考虑将代码从 servlet 中的 <% ... %> 移动并转发到 JPS。
编辑:
JSP 应该只用于呈现信息。准备、计算、数据库操作等都应该在 Servlet 中完成。
你可以在这里阅读更多:How to avoid Java code in JSP files?
在您的情况下:
您创建一个 servlet,将其命名为 PrepareLinkList,然后将上面的脚本代码移到那里:
@WebServlet("/PrepareLinkList")
public class PrepareLinkList extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("testingThings/properties/foo.properties");
Properties props = new Properties();
props.load(stream);
HashMap<String, String> map = new HashMap<String, String>();
for (final String name: props.stringPropertyNames()) {
map.put(name, props.getProperty(name));
}
// make the linkMap attribute available accross the application
getServletContext().setAttribute("linkMap", map);
// response.sendRedirect("dropdown.jsp");
// or
// request.getRequestDispatcher("dropdown.jsp").forward(request, response);
}
}
而在 JSP 中只保留演示文稿:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h3>with map</h3>
<select name="link">
<c:forEach items="${linkMap}" var="link">
<option value="${link.key}">${link.value}</option>
</c:forEach>
</select>
</body>
如您所见,您可以运行一次 PrepareLinkList Servlet,然后在 JSP/Servlet 的所有其他后续请求中访问 linkMap。它减少了代码重复并且易于维护。
在您的情况下,您可以在执行一个假设UpdateLinksProperties-Servlet 后运行/转发/包含PrepareLinkList