我想实现一个单独的JSP标记页面,其形式如下:
JSP:formPay.jsp
<form action="<%=request.getContextPath() + "/Pay.do"%>" method="post" id="guest">
<table>
<tr>
<td width="150"><span class="required">*</span> First Name:</td>
<td><input type="text" name="firstname" value="<%= request.getAttribute("firstname") %>" />
</td>
</tr>
[...]
</table>
<input class="button" type="submit" value="Confirm" name="btnConfirm">
</from>
Servlet:PayCommand.java
public class PayCommand implements Command {
@Override
public HttpServletRequest execute(HttpServletRequest request)
throws ServletException, IOException {
boolean errorWithField = false;
String paramFirstName = "";
String paramLastName = "";
String paramEmail = "";
String paramCity = "";
String paramAddress = "";
try {
paramFirstName = request.getParameter("firstname");
paramLastName = request.getParameter("lastname");
paramEmail = request.getParameter("email");
paramCity = request.getParameter("city");
paramAddress = request.getParameter("address");
} catch (Exception e) {
request.setAttribute("jsp", "formPay");
return request;
}
if (paramFirstName==null || paramFirstName.equals("")) {
errorWithField = true;
}
if (paramLastName==null || paramLastName.equals("")) {
errorWithField = true;
}
if (paramEmail==null || paramEmail.equals("")) {
errorWithField = true;
}
if (paramCity==null || paramCity.equals("")) {
errorWithField = true;
}
if (paramAddress==null || paramAddress.equals("")) {
errorWithField = true;
}
// if errorWithField==true, reload the formPay.jsp
if (errorWithField) {
request.setAttribute("message", "You have to fill out all of the fields.");
request.setAttribute("jsp", "formPay");
request.setAttribute("firstname", paramFirstName);
request.setAttribute("lastname", paramLastName);
request.setAttribute("email", paramEmail);
request.setAttribute("city", paramCity);
request.setAttribute("address", paramAddress);
} else {
// if not, go to the confirm page, everything is ok.
request.setAttribute("jsp", "confirmation");
request.setAttribute("firstname", paramFirstName);
request.setAttribute("lastname", paramLastName);
request.setAttribute("email", paramEmail);
request.setAttribute("city", paramCity);
request.setAttribute("address", paramAddress);
}
return request;
}
}
问题是当JSP第一次加载时,我希望它被解释为好像没有错误,但errorWithField
结果是true
,所以错误信息显示甚至在用户填写表格之前。
第二个问题是JSP将获取已填写的字段的值,但如果没有任何内容,则返回null
,包括第一次加载JSP。我该如何对待这个问题?
修改
请注意,Pay.do
表单操作被重定向到PayCommand.java
,这是由前控制器模式处理的。 (未显示)
答案 0 :(得分:3)
您可以向表单添加隐藏字段,并检查它是否具有值。如果是,那么表格将被回发;否则,它是第一次加载(你应该跳过错误检查的东西)。
答案 1 :(得分:2)
第二个问题,你可以试试这个:
&lt;%= request.getAttribute(“firstname”)== null? “”:request.getAttribute(“firstname”)%&gt;