【问题标题】:Using variables in JSP that have been passed from a servlet?在 JSP 中使用从 servlet 传递的变量?
【发布时间】:2014-06-23 16:46:29
【问题描述】:

我正在尝试在从 servlet 传递的 JSP 中使用 xml 字符串。变量通过正常。我使用代码:

request.setAttribute("xml",xmlDoc_str2);
request.getRequestDispatcher("./jsp/pdirdetail.jsp").forward(request, response);

但是,我不确定如何在 jsp 端使用它。我需要解析它并在 JSP 中读取它。我正在使用代码:

<%=request.getAttribute("xml") %>
<%
        try{
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(${xml}));
        }
        catch(Exception e){}

    %>

它显然不喜欢我引用变量的方式。我不确定是否有其他方法可以做到这一点,或者我是否遗漏了什么。

【问题讨论】:

    标签: java xml jsp servlets


    【解决方案1】:

    您应该尝试使用 XML Tag Library,它为指定和选择 XML 文档的各个部分提供了一种简单的符号。

    问题出在下面一行。不能在 Scriptlet 中混合 JSTL。

    new StringReader(${xml})
    

    始终使用try to avoid Scriptlet 代替JSP Standard Tag Library 或JSP 表达式语言。


    使用 XML 标签库的示例代码:

    XML:

    <books>
    <book>
      <name>Padam History</name>
      <author>ZARA</author>
      <price>100</price>
    </book>
    <book>
      <name>Great Mistry</name>
      <author>NUHA</author>
      <price>2000</price>
    </book>
    </books>
    

    小服务程序:

    // assign the XML in xmlDoc_str2 and set it as request attribute
    request.setAttribute("xml",xmlDoc_str2);
    request.getRequestDispatcher("./jsp/pdirdetail.jsp").forward(request, response);
    

    JSP:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
    
    <html>
    <head>
      <title>JSTL x:parse Tags</title>
    </head>
    <body>
    <h3>Books Info:</h3>
    
    <x:parse xml="${xml}" var="output"/>
    <b>The title of the first book is</b>: 
    <x:out select="$output/books/book[1]/name" />
    <br>
    <b>The price of the second book</b>: 
    <x:out select="$output/books/book[2]/price" />
    
    </body>
    </html>
    

    输出:

    Books Info:
    The title of the first book is:Padam History
    The price of the second book: 2000 
    

    【讨论】:

    • 请注意:问题在于 OP 试图在 scriptlet 中使用表达式语言,这将永远无法工作。
    • @LuiggiMendoza 但 scriplet 也不是正确的方法。让我也解决实际问题。
    • 我对我的问题进行了更改。我正在使用 getAttribute 而不是 getParameter。
    • 如果我使用的是从 servlet 而不是 url 位置获取的变量,我该怎么做?这可能吗?
    • 我在帖子中进行了编辑。只需将 xml 字符串存储为请求属性并使用 EL ${xml} 在 JSP 中访问它。
    猜你喜欢
    • 2013-06-10
    • 2011-04-06
    • 1970-01-01
    • 2013-03-22
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多