I was going through the RequestDispatcher in Head First Servlets and JSP. I am not clear on the following points
- When should we use forward slash(/) in request dispatcher ?
- When should we not use forward slash(/) in request dispatcher ?
- Should the relative path always start with forward slash ?
- Difference between a relative path starting with forward slash(/) and without forward slash(/). For example difference between index.html and /index.html ?
I have tried an example. Below is my project structure and the code
Here is my Servlet Code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String userId = request.getParameter("userId");
String password = request.getParameter("password");
LoginService loginService = new LoginService();
boolean result = loginService.authenticate(userId, password);
if(result){
User userDetails = loginService.getUserDetails(userId);
request.setAttribute("user", userDetails);
//response.sendRedirect("success.jsp");
RequestDispatcher requestDispatcher = request.getRequestDispatcher("success.jsp");
requestDispatcher.forward(request, response);
return;
}else{
response.sendRedirect("/login.jsp");
return;
}
}
My Login page is as follows
My Success Page is as follows
I am validating the logged in user and if the user is a valid user i am forwarding it to the Success page.
Here as per the code when i say
RequestDispatcher requestDispatcher = request.getRequestDispatcher("success.jsp");
requestDispatcher.forward(request, response);
or
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/success.jsp");
requestDispatcher.forward(request, response);
Both ways my control goes to Success.jsp. In Head First JSP and Servlets while reading request dispatcher i was not able to understand the following line and it goes like this
RequestDispatcher requestDispatcher = request.getRequestDispatcher("result.jsp");
This is a relative path because there is not initial forward slash("/").So in this case the container looks for "result.jsp" in the same logical location the request is in.
If the path starts with a forward slash('/") the container sees that as "starting from the root of this webapp". If the path does not start with a forward slash,its considered relative to the original request.
The following are the lines taken from Head First JSP and Servlets.
What does the above lines mean. I am not able to get clear picture of "its considered relative to the original request" Can some one explain with an example.