【问题标题】:Other forms does not work after redirect from Servlet从 Servlet 重定向后其他形式不起作用
【发布时间】:2026-01-22 15:00:01
【问题描述】:

所以,我目前正在尝试学习一些 JSP,但我不知道如何解决我遇到的这个问题。

目前,我有一个包含多个表单的 index.jsp 页面。对于一种表单,它有两个文本字段,将其发送到 servlet test.java 以构建字符串。构建字符串后,servlet 会重定向回 index.jsp

index.jsp原地址: http://localhost:8080/TestJSPConversion/

重定向后,地址为 http://localhost:8080/TestJSPConversion/test

当我尝试在 index.jsp 上使用另一个表单时出现问题,然后它会将我带到地址处的空白页面, http://localhost:8080/TestJSPConversion/test?author=Peter+Johnson

我相信这是由于我用来从 servlet 重定向的方法 (request.getRequestDispatcher("/index.jsp").forward(request, response); 但是,我不太确定如何解决这个问题。即使在 servlet 重定向回 index.jsp 之后,我也希望表单能够正常工作。

Servlet 代码:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    // Get parameters from the request.
    String name = request.getParameter("name");
    String email = request.getParameter("email");

    String message = null;
    GregorianCalendar calendar = new GregorianCalendar();
    if (calendar.get(Calendar.AM_PM) == Calendar.AM) {
        message = "Good Morning, ";
    } else {
        message = "Good Afternoon, ";
    }
    message += name + " with the email, " + email;

    request.setAttribute("message", message);
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

Index.jsp 代码:

<h2>Choose authors:</h2>
<form method="get">
    <input type="checkbox" name="author" value="Tan Ah Teck">Tan
    <input type="checkbox" name="author" value="Mohd Ali">Ali 
    <input type="checkbox" name="author" value="Kumar">Kumar 
    <input type="checkbox" name="author" value="Peter Johnson">Peter
    <input type="submit" value="Query">
</form>

<c:set var="authorName" value="${param.author}" />
</br>
<c:if test="${not empty authorName}">
    <c:out value="${authorName}" />
</c:if>
</br>
<form  action="test" method="POST">  
    First Name: <input type="text" name="name" size="20"><br />  
    Surname: <input type="text" name="email" size="20">  
    <br /><br />  
    <input type="submit" value="Submit">  
</form>
<c:out value="${message}" /> 

【问题讨论】:

  • 当您提交其他表单时,他们是否有 action="someServlet" 其中 someServlet 是现有的 servlet ??
  • 另一种形式只是从复选框中获取作者姓名并显示它,所以它没有。

标签: java jsp servlets jstl


【解决方案1】:

也为其他 &lt;form&gt; 设置 action="test"。

如果这会引导您访问一些 url,例如 domain/TestJspConnection/test/test... 然后尝试将 action="/TestJSPConnection/test" 作为您的 &lt;form&gt; 属性

哦,是的,根本没有注意到这一点!...您没有在您的 sevlet 中实现 doGet()...所以 &lt;form method="get" &gt; 将您带到空白页面

所以..两种解决方案:

1) 在 servlet 中实现 doGet()

2) 为第一种形式设置method="post"

【讨论】:

【解决方案2】:

尝试response.sendRedirect("index.jsp?message=hello"); 并使用${param.message} (EL) 显示它。如果你使用&lt;form action="test" method="POST"&gt;中的方法作为post,那么你必须在doPost方法中编写代码。

【讨论】:

  • 维斯鲁斯,你是英雄。
【解决方案3】:

首先:您只实现 doPost,因此您的第一个带有 method=Get 的表单将很可能。失败。

第二:你应该使用 sendRedirect 而不是 forward。这样,如果您在浏览器上点击刷新,您将不会收到有关重新发布数据的警告!当服务器进程完成并且您希望在 JSP 中显示结果时,最好使用 sendRedirect。

问候

【讨论】: