重定向到同一页面的结果是空白页。

问题描述 投票:-1回答:1

我正在创建一个 java servlet网络应用程序,在这里我接受用户的输入。index.jsp 并显示结果在 result.jsp 一页页 POST 动作。在提交表单之前,我先验证用户的输入。如果发现了任何验证错误,我就会 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>
java jsp tomcat servlets jstl
1个回答
0
投票

req.getRequestDispatcher()return 方法中隐含的。如果你没有提到 return 显式,即时行也会被编译器执行。正如 @BalusC 所说 乱了方寸 通过执行两个 req.getRequestDispatcher() 连续的声明。

要么你需要 return 明确-

if (hasError) {
    req.getRequestDispatcher("/index.jsp").forward(req, resp);
    return;
}

req.getRequestDispatcher("/result.jsp").forward(req, resp);

或者,把后面的那个放在里面 else 块 -

if (hasError) {
    req.getRequestDispatcher("/index.jsp").forward(req, resp);
} else {
    req.getRequestDispatcher("/result.jsp").forward(req, resp);
}

© www.soinside.com 2019 - 2024. All rights reserved.