Issue
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
I thought I understand it, until I tried it out. I will put super simple code for demonstration:
Starts with 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:
@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:
<html><body>
hellooooo
</body></html>
After I run it, I get hellooo
message. But once I change redirect to /test.jsp
instead of test.jsp
, I get not found error.
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
If Head First told me that /
stands for root
, why am I not getting same URL as in first case? Root = testProject, right? Can anyone spot what am I saying wrongly?
Solution
Root = testProject? NO!
The root path is the doman part without any path,which is http://localhost:8080 in you context.
For example, suppose the current request url is http://localhost:8080/a/b
, if you call resp.sendRedirect("c");
, the next request url is http://localhost:8080/a/c
. If you call resp.sendRedirect("/c");
, the next request url will be http://localhost:8080/c
.
Answered By - haoyu wang