我会继续这样说:
- 负荷特性(像你这样)
- 填补了地图(因为键和值很容易与JSP-EL访问)
- 将地图设置为页面属性(可从JSP-EL访问)
- 通过地图(使用Core JSTL)
- 使用
key
和填充选项标记
像这样:
<%@ 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使用小脚本。
您应该考虑将代码从<% ... %>
移到servlet中并转发到JPS。
编辑:
JSP应该只用于呈现信息。准备,计算,数据库操作等应该在Servlets中完成。
你可以在这里阅读更多:How to avoid Java code in JSP files?
你的情况: 您创建一个servlet,让我们将其命名为PrepareLinkList
,并从上面有移动scriplet代码:
@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,并访问linkMap
在JSP/Servlet的所有其他请求中。它减少了代码重复并且易于维护。
在你的情况,你可以运行/前进/包括PrepareLinkList
后一个的执行可以说UpdateLinksProperties
-servlet
谢谢,我知道了。但我不知道这意味着什么:“您应该考虑将代码从<% ... %>移到servlet中并转发到JPS” – Lazloman
好吧,我现在明白了。非常感谢。 – Lazloman