我想实现一个像这样的表单的 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>
小服务程序: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
,这是处理前端控制器模式。(未显示)