我有一个共享JavaBean实例的servlet和JSP-- servlet初始化它们(因为bean需要构造函数params)并将它们存储在会话中,然后转发到获取用户输入并通过a提交回servlet的JSP。表单POST请求。在servlet的doPost
方法中,它再次检索JavaBeans,但是由表单设置的所有值都为null。如果我在表单上使用GET方法而不是填充值,并且在调试时我可以看到JavaBean属性值实际上是设置的。那么为什么我的doPost
方法从会话中使用空值检索bean?有趣的是,通过每个对象的构造函数参数传入的字段实际上是正确设置的,无论是GET还是POST - 它只是通过表单管理的未设置的属性。
缩写代码示例
的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>
当我在此表单中输入数据并单击“下订单”时,toString()调用的输出会将customer
和address
的所有字段显示为空。
答案 0 :(得分:0)
所以似乎我不可能 - <jsp:setProperty ... property="*" />
是我需要的,但是在我提供另一个JSP之前它是不可用的,我想在之后 / em>访问servlet中的bean。所以我可以做以下其中一项: