I have a servlet and JSP which share JavaBean instances – the servlet initialises them (since the beans require constructor params) and stores them in the session, then forwards to a JSP which gets user input and submits back to the servlet via a form POST request. In the servlet’s doPost method it retrieves the JavaBeans again, but all of its values that would have been set by the form are null. If I use the GET method on the form instead then the values are populated, and whilst debugging I can see that the JavaBean property values are in fact set. So why does my doPost method retrieve beans from the session with null values? Interestingly, the fields that are passed in through constructor parameters of each object are in fact set correctly whether it’s GET or POST – it’s just those properties managed through the form that aren’t set.
Abbreviated code samples
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
Customer customer = (Customer)session.getAttribute("customer");
if (customer == null)
{
customer = new Customer(.....);
session.setAttribute("customer", customer);
}
Address address = (Address)session.getAttribute("address");
if (address == null)
{
address = new Address(.....);
session.setAttribute("address", address);
}
forward("/checkout.jsp", request, response);
}
...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
Customer customer = (Customer)request.getSession().getAttribute("customer");
if (customer != null)
{
out.println("Customer: " + customer.toString());
}
Address address = (Address)request.getSession().getAttribute("address");
if (address != null)
{
out.println("Address: " + address.toString());
}
}
JSP
<jsp:useBean id="customer" class="com.mycompany.myproject.Customer" scope="session" />
<jsp:setProperty name="customer" property="*"/>
<jsp:useBean id="address" class="com.mycompany.myproject.Address" scope="session" />
<jsp:setProperty name="address" property="*"/>
...
<form method="POST" action="${pageContext.request.contextPath }/checkout">
<table>
<tr>
<td>Title</td>
<td><input type="text" name="title" value="${ customer.title }" /></td>
</tr>
<tr>
<td>Given name</td>
<td><input type="text" name="givenName" value="${ customer.givenName }" /></td>
</tr>
...
</table>
<input type="submit" value="Place order" />
</form>
When I enter data into this form and click ‘Place Order’ the output of the toString() calls show all the fields of customer and address as null.
So it seems that what I wan’t isn’t possible – the
<jsp:setProperty ... property="*" />is what I need but it isn’t available until I serve up another JSP, which I want to do after accessing the bean in the servlet. So I can do one of the following: