1

Note : This question is already answered in the following link , the only difference is that in this question I just want to send a specific value other than a complete object.

I want to create a form in which along with input value i also want to send a value from JSP to servlet with setAttribute() method.

Example

demo1.jsp

<form method="POST" action="DEMO1">
<% request.setAttribute("value",1); %>
<input type="submit" value="Add" />
</form>

DEMO1

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    PrintWriter pw=response.getWriter();
    pw.println(request.getAttribute("value"));
}

It prints a null value when i used to post my page. Is there any process where I can access the setAttribute() value at jsp in servlet.

1 Answers1

2

You need to understand the sequence of processing here. When you do request.setAttribute("value",1);, that is simply setting the attribute value on the current request object which cease to exist as soon as you return the HTML form to the user. When the user submits the form, there is no attribute called 'value' in the form. So when your servlet tries to retrieve it from the request object, it is returned as null because it doesn't exist.

User a hidden input to store the value you want your server to receive when the form is submitted.

<input type="hidden" name="value" value="1" />

So your demo JSP will look like following:

<form method="POST" action="DEMO1">
   <input type="hidden" name="value" value="1" />
   <input type="submit" value="Add" />
</form>
VHS
  • 9,534
  • 3
  • 19
  • 43
  • Is there no way to access that value... – SATYA PRAKASH NANDY Oct 10 '17 at 20:01
  • Thank you . but i still have problem in understanding that why the value inside the text or hidden present after we post the page and why the setAttribute() is unable to do that. and how request scope actually work. will you please explain me ... need help. – SATYA PRAKASH NANDY Oct 10 '17 at 20:12
  • Any input attribute that is on the form that is not disabled is submitted with the form. The attributes are automatically populated in the 'request' object with the key as the `name` of the attribute and value as the `value` of the attribute. – VHS Oct 10 '17 at 20:17