I have a JSP that contains a form, containing several text inputs.
I can fill the text inputs with some data.
Once I click the submit button, my servlet’s doPost method is called, as expected.
Following the PRG design pattern, I use a “sendRedirect” call at the end of the doPost method, to avoid a second submission of my form if, for instance, the user reloads the wep page.
At this point everything is OK :
The data entered in the form are displayed on screen.
But, if I press on the submit button again, I get nasty nullPointerExceptions, because the HttpServletRequest that is passed to the doPost method of my servlet does not contain anymore the data I entered on the first submit.
I don’t understand why I get this behaviour:
The form contains the data, but it does not send it the second time.
Can you explain me what is wrong in my approach ?
[EDIT] I’m trying another approach, by using session attributes
here is some of my code:
on the JSP (myJsp.jsp)
<form method="post" action="myServlet">
field: <input type="text" name="field" value="${sessionScope.bean.field}"><br>
<input type="submit" name="lastname">
</form>
on the servlet (myServlet.java)
private Bean myBean;
doPost(...){
doSthWithMyBean(myBean);
response.sendRedirect("myJsp.jsp");
}
doGet(...){
request.getSession().setAttribute("bean",myBean);
this.getServletContext()....("myJsp.jsp").forward(request, response);
//I forget the exact methods on the description above, but you see what I do : I forward the request and response to the same jsp
}
What I understand :
– when the page is loaded for the first time, the doGet method is called. So myBean is set as an attribute of the session
– when I hit submit, the doPost method is called. Since myBean has already been set as an attribute for the session, I expect to retrieve automatically the bean info (since ${sessionScope.bean.field} is in the value field of the form)
=> With this second approach, even the first form submission fails with null pointer exception, but I don’t understand why.
If I revert back to using request parameters instead of session object
value="${bean.field}
I access the parameter via request.getParameter in the doPost method.
It works for the first submission of the form, but on the second submission, even if the form is filled with the value from the first submission, there is no request parameter named “field”.
To sum up all my talking :
– when I use request parameter : why is there no request parameter named “field” on the second submission ?
– when I use session attribute : why is it null on the first form submission ?
using #{…} EL expression works