Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need assistance with attributes in JSP

 
Randall Stevens
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two servlets which communicate to different JSPs. One works as expected, the other does not work at all.
Originally both servlets used getServletContext().setAttribute("inputValue",inPutObj); and the JSPs did a <%=getServletContext().getAttribute("inputValue")%> and both of them worked except that all users received the same value for "inputValue".
To get around this problem, I changed both servlets to use request.setAttribute("inputValue",inPutObj) and changed both JSPs to use <%=request.getAttribute("inputValue")%>, only one of the servlet/jsp pairs works.
The one that does not work is called directly by the servlet name, and only sends data to a JSP in an error situation. The one that does work, is called via a "POST" from an HTML page.
By not working, the JSP shows the word null where it should show my error code. Per my logging, a valid value is placed in inPutObj but does not get to the error.jsp file.
Any help would be appreciated.
 
Mark Latham
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since it does work when the variable's scope is at the ServletContext, but doesn't work when the variable's scope is at the request level then there's likely a problem with how the request is being forwarded.
If you'd like to keep the variable at the request level (which should work and you should do), please provide some details on how you're forwarding to the JSP.
Alternatively, simply put and retrieve the variable from the session.
And, since you mentioned that the servlet you POST to works and the servlet you GET doesn't, please be sure you're setting the variable in the doGet() method and not the doPost() method.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64827
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
both of them worked except that all users received the same value for "inputValue"

There is one servlet context per web application, so any attributes you put into this context will be shared.
is called via a "POST" from an HTML page.

Attributes placed onto a request will only be available during the lifetime of that particular request. This is why you saw the attribute "work" when the servlet forwards to a JSP, but not after the request has finished and the next page (containing your posting form or whatever) is displayed in the browser.
To use per-user attributes that have a lifetime extending across requests, you should place the attribute in session scope.
bear
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic