jordaniac89
jordaniac89

Reputation: 574

Using variables in JSP that have been passed from a servlet?

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.

Upvotes: 0

Views: 157

Answers (1)

Braj
Braj

Reputation: 46841

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 

Upvotes: 1

Related Questions