java—sendredirect(test.jtp)和sendredirect(/test.jsp)之间的区别

oiopk7p5  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(329)

我要注意 / 用于重定向。
正斜杠开头的意思是“相对于这个web容器的根-头优先的jsp和servlet
我以为我能理解,直到我试过。我将用超级简单的代码来演示:
以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 ,我没有找到错误。
我还注意到,当我使用redirect(test.jsp)时,我发现http://localhost:8080/testproject/index.html。但是,当我使用redirect(/test.jsp)时,我得到:http://localhost:8080/test.jsp
如果海德先告诉我的话 / 代表 root ,为什么我没有得到第一种情况下相同的网址?root=testproject,对吗?谁能看出我说错了什么?

pu3pd22g

pu3pd22g1#

根=测试项目?不!
根路径是没有任何路径的域部分,即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 .

相关问题