【发布时间】:2020-10-07 12:14:57
【问题描述】:
我正在创建一个java servlet Web 应用程序,我在index.jsp 处获取用户输入,并在POST 操作时在result.jsp 页面上显示结果。在提交表单之前,我会验证用户输入。如果发现任何验证错误,我希望 redirect 用户访问带有错误消息的同一 index.jsp 页面。但是redirect 操作会导致空白页。这是我到目前为止所做的 -
Servlet 类doPost 方法 -
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
//this is just a dto class
CovidQa covidQa = new CovidQa(name);
CovidTestValidator validator = new CovidTestValidator();
boolean hasError = validator.validate(covidQa, req);
if (hasError) {
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}
req.getRequestDispatcher("/result.jsp").forward(req, resp);
}
验证者的validate方法-
public boolean validate(CovidQa covidQa, HttpServletRequest request) {
boolean hasError = false;
if (covidQa.getName() == null || covidQa.getName().equals("")) {
request.setAttribute("nameErr", "Name can not be null");
hasError = true;
}
return hasError;
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Covid-19</servlet-name>
<servlet-class>CovidTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Covid-19</servlet-name>
<url-pattern>/Cov</url-pattern>
</servlet-mapping>
</web-app>
index.jsp -
<form action="Cov" method="post">
//input fields
<label>Name</label>
<input type="text"
id="name"
name="name">
<span>${nameErr}</span>
<button type="submit">Submit</button>
</form>
【问题讨论】:
-
1) 你根本没有重定向。你在转发。 2) 当出现错误时,您将转发到 index.jsp,然后再转发到 result.jsp。显然,系统混乱了。您不应该在逻辑上将结果转发到 else 块中吗?
标签: java jsp tomcat servlets jstl