简体   繁体   English

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

[英]Difference between sendRedirect(test.jsp) and sendRedirect(/test.jsp)

I want to pay attention to / used in redirect.我想注意/用于重定向。

Forward slash at the beginning means "relative to the root of this web container - Head First JSP and Servlets开头的正斜杠表示“相对于此 web 容器的根 - Head First JSP 和 Servlets

I thought I understand it, until I tried it out.我以为我理解它,直到我尝试了它。 I will put super simple code for demonstration:我将放置超级简单的代码进行演示:

Starts with index.html:以 index.html 开头:

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

Then it goes to GenericServlet.class:然后转到 GenericServlet.class:

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

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

, which redirects to test.jsp: ,重定向到 test.jsp:

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

After I run it, I get hellooo message.运行后,我收到hellooo消息。 But once I change redirect to /test.jsp instead of test.jsp , I get not found error .但是,一旦我将重定向更改为/test.jsp而不是test.jsp ,我就找不到错误

I also noticed when I use redirect(test.jsp), I get this http://localhost:8080/testProject/index.html .But, when I use redirect(/test.jsp), I get this: http://localhost:8080/test.jsp我还注意到,当我使用重定向(test.jsp)时,我得到了这个http://localhost:8080/testProject/index.html 。但是,当我使用重定向(/test.jsp)时,我得到这个: Z80791B3AE7002FAA8CEF82468/77 /localhost:8080/test.jsp

If Head First told me that / stands for root , why am I not getting same URL as in first case?如果 Head First 告诉我/代表root ,为什么我没有得到与第一种情况相同的 URL ? Root = testProject , right? Root = testProject对吧? Can anyone spot what am I saying wrongly?谁能发现我说错了什么?

Root = testProject ?根 = 测试项目 NO!不!

The root path is the doman part without any path,which is http://localhost:8080 in you context.根路径是没有任何路径的域部分,在你的上下文中是http://localhost:8080

For example, suppose the current request url is http://localhost:8080/a/b , if you call resp.sendRedirect("c");例如,假设当前请求 url 为http://localhost:8080/a/b ,如果调用resp.sendRedirect("c"); , the next request url is http://localhost:8080/a/c . ,下一个请求 url 是http://localhost:8080/a/c If you call resp.sendRedirect("/c");如果你调用resp.sendRedirect("/c"); , the next request url will be http://localhost:8080/c . ,下一个请求 url 将是http://localhost:8080/c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM