我将以这种方式进行:
- 加载属性(就像您所做的一样)
- 填写地图(因为键和值可通过JSP-EL轻松访问)
- 在页面属性中设置地图(可从JSP-EL访问)
- 遍历地图(使用Core 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 propertiesInputStream stream = application.getResourceAsStream("foo.properties");Properties props = new Properties();props.load(stream);// 2. fill a mapHashMap<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 attributepageContext.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中完成。
在您的情况下:创建一个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,然后访问
linkMapJSP /
Servlet的所有其他后续请求。它减少了代码重复,并且易于维护。
在您的情况下,您可以运行/转发/包含
PreparelinkList执行后的
UpdatelinksProperties-Servlet



