我有一个共享 JavaBean 实例的 servlet 和 JSP - servlet 初始化它们(因为 bean 需要构造函数参数)并将它们存储在会话中,然后转发到 JSP,它获取用户输入并通过表单 POST 请求提交回 servlet . 在 servlet 的doPost
方法中,它再次检索 JavaBean,但它的所有值都将由表单设置为空。如果我在表单上使用 GET 方法,则填充值,并且在调试时我可以看到 JavaBean 属性值实际上已设置。那为什么我的doPost
方法从会话中检索具有空值的 bean?有趣的是,通过每个对象的构造函数参数传入的字段实际上是正确设置的,无论是 GET 还是 POST——只是那些通过表单管理的属性没有设置。
缩写代码示例
小服务程序
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>
当我在此表单中输入数据并单击“下订单”时,toString() 调用的输出将 和 的所有字段显示customer
为address
空。