我能够提交我的表单,将数据推送到数据库中,并以我的 servlet 成功/错误消息结束。但我仍然需要将其重定向回带有相关结果的表单 html:
1)成功覆盖(现有的javascript方法被触发)和所有表单字段为空
2) 错误消息(表单字段仍包含输入值)
这些是我目前拥有的代码和文件(提取):
表单.java
protected void contructAndSendResponse(HttpServletResponse response, String responseStatus, String... responseErrorCodes) throws Exception {
StringBuilder responseMsg = new StringBuilder();
responseMsg.append(Form.RESPONSE_DATA_STATUS);
responseMsg.append(responseStatus);
if (responseErrorCodes == null || responseErrorCodes.length == 0) {
responseMsg.append(Form.JSON_CLOSE_OBJECT);
}
else {
responseMsg.append(Form.RESPONSE_DATA_ERROR_CODE);
responseMsg.append(Form.JSON_BEGIN_ARRAY);
int errorCodeLength = responseErrorCodes.length;
for (int i = 0; i < errorCodeLength; i++) {
responseMsg.append(Form.JSON_DOUBLE_QUOTE);
responseMsg.append(responseErrorCodes[i]);
responseMsg.append(Form.JSON_DOUBLE_QUOTE);
if (i < errorCodeLength - 1) {
responseMsg.append(Form.JSON_COMMA);
}
}
responseMsg.append(Form.JSON_END_ARRAY);
responseMsg.append(Form.JSON_CLOSE_OBJECT);
}
contructAndSendResponse(response, responseMsg.toString());
}
protected void contructAndSendResponse(HttpServletResponse response, String responseMsg) throws Exception {
ServletOutputStream outStream = response.getOutputStream();
response.setContentType(Util.CONTENT_TYPE_JSON);
outStream.print(responseMsg);
outStream.flush();
outStream.close();
}
public void returnResponse(HttpServletResponse response, String responseStatus, String... responseErrorCodes) {
try {
contructAndSendResponse(response, responseStatus, responseErrorCodes);
}
catch (Exception e) {
}
}
Servlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Form onlineForm = null;
List<String> errorCodes = new ArrayList<String>();
try {
onlineForm = FormFactory.getInstance().createObject(formtype);
onlineForm.extractRequest(request);
errorCodes = onlineForm.validateInputParam();
if (errorCodes == null || errorCodes.isEmpty()) {
Connection conn = PersistentFactory.getInstance().openConnection();
responseStatus = Form.RESPONSE_DATA_STATUS_SUCCESS;
PersistentFactory.getInstance().closeConnection(conn);
}
}
catch (Exception e) {
errorCodes.add(EntityUtils.ErrorCode.E1.name());
}
onlineForm.returnResponse(response, responseStatus, errorCodes.toArray(new String[0]));
}
表单.jsp
<form id="form" action="/projectx/form?type=contact" class="custom-ui" method="POST" >
....
</form>
<script type="text/javascript">
function overlay(){
Projectx.modalDialog({
elem: "#form",
title: "Success",
body: "Thank you",
tpl: "modal-tpl"
});
}
</script>
我已经尝试过这些,但重定向不适用于我上面的代码:
- dispatcher.forward(request,response);
- forward(responsePage, aRequest, aResponse);
- redirect(responsePage, response);