sendRedirect(test.jsp) 和 sendRedirect(/test.jsp) 的区别

Difference between sendRedirect(test.jsp) and sendRedirect(/test.jsp)

我要注意重定向中使用的/

Forward slash at the beginning means "relative to the root of this web container - Head First JSP and Servlets

我以为我明白了,直到我尝试了一下。我将放上超级简单的代码进行演示:

开头为 index.html:

<html><body>
    <form action="GenericServlet" method="POST">
        Enter name: <input type="text" name="name">
        <button>Submit name</button>
    </form>
</body></html>

然后转到GenericServlet.class:

@WebServlet("/GenericServlet")
public class GenericServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        resp.sendRedirect("test.jsp");
        
    }
}

,重定向到 test.jsp:

<html><body>
hellooooo
</body></html>

在我 运行 它之后,我收到 hellooo 消息。但是一旦我将重定向更改为 /test.jsp 而不是 test.jsp,我就会收到 not found 错误 .

我也注意到当我使用重定向(test.jsp)时,我得到这个 http://localhost:8080/testProject/index.html .但是,当我使用重定向(/test.jsp)时,我得到这个:http://localhost:8080/test.jsp

如果 Head First 告诉我 / 代表 root,为什么我得到的 URL 与第一种情况不同? Root = testProject,对吧?谁能看出我说错了什么?

根=测试项目?不!

根路径是没有任何路径的doman部分,在你的上下文中是http://localhost:8080

例如,假设当前请求url是http://localhost:8080/a/b,如果调用resp.sendRedirect("c");,下一个请求url是http://localhost:8080/a/c。如果您调用 resp.sendRedirect("/c");,下一个请求 url 将是 http://localhost:8080/c