0

I'm trying to use an xml string in a JSP that I've passed from a servlet. The variable passes fine. I use the code:

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

However, I'm not sure how to use it on the jsp end. I need to parse it and read it in the JSP. I'm using the code:

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

    %>

It apparently doesn't like the way I'm referencing the variable. I'm not sure if there's another way to do this or if I'm missing something.

jordaniac89
  • 574
  • 2
  • 8
  • 27

1 Answers1

1

You should try with XML Tag Library that provides an easy notation for specifying and selecting parts of an XML document.

The problem is at below line. You can't mix JSTL inside Scriptlet.

new StringReader(${xml})

Always try to avoid Scriptlet instead use JSP Standard Tag Library or JSP Expression Language.


Sample code using XML Tag Library:

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>

Servlet:

// 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>

output:

Books Info:
The title of the first book is:Padam History
The price of the second book: 2000 
Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • 2
    Just to note: the problems are that OP's trying to use Expression Language inside scriptlet, which won't work ever. – Luiggi Mendoza Jun 23 '14 at 16:53
  • @LuiggiMendoza but scriplet is also not the correct way. Let me address the actual issue as well. – Braj Jun 23 '14 at 16:54
  • I made a change to my question. I'm using getAttribute instead of getParameter. – jordaniac89 Jun 23 '14 at 16:59
  • How would I do that if I was using a variable that was taken from a servlet instead of a url location? Is that possible? – jordaniac89 Jun 23 '14 at 18:13
  • I have edited in my post. Simply store the xml string as request attribute and use EL `${xml}` to access it in JSP. – Braj Jun 23 '14 at 18:44