Is it possible to use request.setAttribute on a JSP page and then on HTML Submit get the same request attribute in the Servlet?
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.
If you want to persist attributes through requests you need to either:
- Have a hidden input in your form, such as
<input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />
. This will then be available in the servlet as a request parameter. - Put it in the session (see
request.getSession()
- in a JSP this is available as simplysession
)
I recommend using the Session as it's easier to manage.
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails: <% SubFamily subFam=(SubFamily)request.getAttribute("SUBFAMILY"); request.setAttribute("SUBFAMILY"); %>
Where as the same thing has worked in case of page 1 like:
<% request.setAttribute("SUBFAMILY"); %>
So I think I would need to proceed with either of the two options suggested by Phill.
The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.
i think phil is right request option is available till the page load. so if we want to sent value to another page we want to set the in the hidden tag or in side the session if you just need the value only on another page and not more than that then hidden tags are best option if you need that value on more than one page at that time session is the better option than hidden tags.
Try request.getSession().setAttribute("SUBFAMILY", subFam); request.getSession().getAttribute("SUBFAMILY");