Reputation: 21393
I am practicing JSP with small programs and came across small issue.
I have my first jsp page with a form and a code that sets the request attribute.
<form action="process.jsp" method="post">
User: <input type="text" name="userName">
<br/><br/>
<input type="submit" value="Submit"/>
</form>
<%request.setAttribute("sampleKey","myValue");%>
This is how my process.jsp
looks like:
Welcome <%=request.getParameter("userName")%>
<br/>
The attribute is <%=request.getAttribute("sampleKey")%>
When I access first page and submit to process.jsp page then I was expecting the request attribute will have its value, but I am getting null
here.
This is just a sample program for learning, I am aware that we should not use scriplets.
What is the issue here, can you please tell me?
Upvotes: 3
Views: 5473
Reputation:
Problem is you are using html from to submit request to process.jsp
. Hence your request attribute gets lost.
Option 1, Use hidden
field in the same form and get it using req.getParameter()
.
Option 2, Use session
attribute instead of request
.
Upvotes: 0
Reputation: 26
The issue is in <% request.setAttribute("sampleKey","myValue"); %> this code because of request . use
instead ofand then you can get in process.jsp page by this type .
session.getAttribute("sampleKey");
Upvotes: 0
Reputation: 51711
The issue is that when you submit the <form>
, it makes a new POST
request to process.jsp and hence any request
attributes set before aren't available anymore. What you need is to use the session
scope instead, which will keep its attributes across several requests coming from the same user.
So, in your JSP form a session attribute set as
<% session.setAttribute("sampleKey","myValue"); %>
can then be retrieved in your process.jsp as
Welcome ${param.userName}
<br/>
The attribute is ${sampleKey}
Upvotes: 3