0

I have a Servlet, which sends values to a JSP1. I am setting the values in the servlet as

request.setAttribute();

and i am using

dispatcher.forward(request, response);

and i am able to access these values in the JSP1 using expression language.

Now, I also need to use this in another JSP2.

These two JSP's are clubbed together to display in a single page. So, I need to access the values of the servlet in the second jsp as well. How can i do that?

  • how are you forwarding the request from jsp1 to jsp2 – shikjohari Jan 23 '15 at 05:30
  • use session to store its value so it can be accessed on any page you want – singhakash Jan 23 '15 at 05:33
  • How are the two jsp *clubbed* together ? If you are simply using inclusion (`@include` or ``), no problem : they use same request and both will access the request attributes. If it is anything else (ajax, portlet, ...) pleas say what you use. – Serge Ballesta Jan 23 '15 at 07:03

2 Answers2

0

It is quite simple. If you are setting an attribute "attr1" in a servlet and then forwarding to a JSP (file1.jsp):

request.setAttribute("attr1", "first attr");
request.getRequestDispatcher("file1.jsp").forward(request, response);

And suppose in the first JSP (file1.jsp), you are including another JSP (say file2.jsp):

<body>
.....
<jsp:include page="file2.jsp"></jsp:include>
.....
</body>

Then in file2.jsp, you can access attr1 by calling the request object's getAttribute method:

<body>
....
${attr1}
....
</body>

In case of jsp:include action, when file2.jsp is included in file1.jsp, both request and response objects are passed to file2.jsp as parameters. So file2.jsp can access the attributes of file1.jsp's request object.

Haris
  • 757
  • 1
  • 7
  • 10
  • Please dont advise using the scriptlets _they are discouraged over the decades_. have a look http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files – Santhosh Jan 23 '15 at 07:07
0

As you say you have both the jsp clubbed in a single page , you can simply get the attribute as,

   ${attributeName}

it refers to the object set in the HttpServletRequest scope . I suggest to take the tutorial for Expression language

Santhosh
  • 8,181
  • 4
  • 29
  • 56