栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从jsp属性文件填充选择

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从jsp属性文件填充选择

我将以这种方式进行:

  1. 加载属性(就像您所做的一样)
  2. 填写地图(因为键和值可通过JSP-EL轻松访问)
  3. 在页面属性中设置地图(可从JSP-EL访问)
  4. 遍历地图(使用Core JSTL)
  5. 使用
    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,然后访问

linkMap
JSP /
Servlet的所有其他后续请求。它减少了代码重复,并且易于维护。

在您的情况下,您可以运行/转发/包含

PreparelinkList
执行后的
UpdatelinksProperties
-Servlet



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/466662.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号