0

How to pass object in java servlet to JSP file?

This post's answer by Matthew Abbott seems easy, but I'm not able to get it to work. I must be missing something obvious.

In my java servlet:

 request.setAttribute("testData", "TEST");
 request.getRequestDispatcher("/WEB-INF/myFile.jsp").include(request, response);

myFile.jsp is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML lang='en'>
<HEAD>
    <TITLE>My Page</TITLE>
</HEAD>

<BODY>
  <p>${testData}</p> 
</BODY>
</HTML>

But this simply displays ${testData} rather than TEST.

If I change myFile.jsp as follows, it works fine, but I understand scriplets are discouraged:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML lang='en'>
<HEAD>
    <TITLE>My Page</TITLE>
</HEAD>

<BODY>
  <% 
     String testData = (String) request.getAttribute("testData");
     out.println(testData);
  %>
</BODY>
</HTML>
Community
  • 1
  • 1
user46688
  • 733
  • 3
  • 11
  • 29

2 Answers2

1

Try adding this to your JSP:

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

JSTL also has a dependency:

<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
BillFromHawaii
  • 334
  • 1
  • 7
  • I think your uri is slightly off (I get a blank page). But, I did see a similar line in this post: `http://stackoverflow.com/questions/20501595/pass-data-from-servlet-to-jsp-without-forms?rq=1`, but it didn't make a difference. – user46688 Oct 23 '14 at 00:29
  • I just think that the feature you're trying to use is part of JSTL. I googled the uri, probably old. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> is probably right. JSTL has a dependency as well. – BillFromHawaii Oct 23 '14 at 00:40
  • Where should `` get added? – user46688 Oct 23 '14 at 01:23
  • If you're using maven then with your dependencies in your pom.xml. If not then get the jar file (jstl-1.2.jar) from http://stackoverflow.com/tags/jstl/info and put it in your classpath /WEB-INF/lib. – BillFromHawaii Oct 23 '14 at 01:37
  • Thanks, I'm not using Maven. I'm coding everything by hand in a text editor. – user46688 Oct 23 '14 at 02:05
  • Ok, so get the jar and put it in /WEB-INF/lib. – BillFromHawaii Oct 23 '14 at 02:14
0

You're trying to use EL which could be disabled. Try adding this to the page:

<%@ page isELIgnored="false" %>
fgb
  • 18,439
  • 2
  • 38
  • 52
  • This makes the page go blank. No sure where I'm supposed to insert it, so I tried inserting inside `` tags, as well as (separately) before ` – user46688 Oct 23 '14 at 01:21