0

I was going through the RequestDispatcher in Head First Servlets and JSP. I am not clear on the following points

  1. When should we use forward slash(/) in request dispatcher ?
  2. When should we not use forward slash(/) in request dispatcher ?
  3. Should the relative path always start with forward slash ?
  4. 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 Project Structure

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

Login Page

My Success Page is as follows

Success Page

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.

Avinash Reddy
  • 2,204
  • 3
  • 25
  • 44

3 Answers3

1

If you are here.

http://www.example.com/one/two/three/four/five.jsp

and you redirect to six.jsp by request.getRequestDispatcher("six.jsp").forward(req, resp);, then you land on

http://www.example.com/one/two/three/four/six.jsp      (relative path)

BUT

If you redirect to /six.jsp by request.getRequestDispatcher("/six.jsp").forward(req, resp);, then you land on

http://www.example.com/six.jsp      (starting from root)
Shrinivas Shukla
  • 4,325
  • 2
  • 21
  • 33
  • The request dispatcher doesn't perform a redirect at all. – BalusC Aug 05 '15 at 18:36
  • @BalusC updated my answer. Sorry for the incomplete statement. Thanks for pointing it out :) – Shrinivas Shukla Aug 05 '15 at 18:49
  • The problem was not the statement. The problem was the terminology. A forward is not the same as a redirect. – BalusC Aug 05 '15 at 18:52
  • Should I change it to `response.sendRedirect();` ? – Shrinivas Shukla Aug 05 '15 at 18:55
  • No. Question was about request dispatcher. You only keep telling "you redirect to" but the given code doesn't perform a redirect at all. It performs a forward. You should be saying "you forward to". Do note that the OP already used the correct term "forwarding". Moreover, the URL in browser's address bar won't change when you perform a forward. So the part "you land on" is also confusing. Food for read: http://stackoverflow.com/a/2048640 – BalusC Aug 05 '15 at 18:58
0

Absolute and relative paths have different pros and cons.

If you are sure that you have a bunch of servlets (jsp being servlets) all at the same hierarchy level, and if you do not want to be bothered with what this hierarchy (prefix) is, then relative URLs are appropriate. A real example use case would be servlets of a REST server behind a javascript front server - angularjs developpers often use relative paths for the REST service

On the opposite, if you want to be able to easily change the URL hierarchy in a full web application, absolute URLs are the way to go. But in that case, you must take into account the servlet context path, because you will forward to a local path but redirect to a full path, with :

full_path = servlet_context_path/local_path

Almost real example: if a webapp is deployed on http, port 8080 on host host.domain in webapp, the page /subdomain1/page1 will have a full URL of http://host.domain:8080/webapp/subdomain/page1, you will use /subdomain/page1 in forward and /webapp/subdomain/page1 in redirect or links.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

A forward slash at the beginning of a URN will redirect to the root of the application container/server and its absence in a URN will redirect relative to the URL requested by the client.

The forward slash '/' character is used in JSPs within links eg:

<a href="/foo/stuff.htm">Stuff page</a>

and in servlets by the RequestDispatcher.forward() and HTTPResponse.sendRedirect() methods for URL redirections.

It only has an effect when applied at the beginning of your redirection url.

Here are the rules for how it is interpreted behind the scenes by the your application server:

  1. First of all: Please be aware that the redirection address is always CASE SENSITIVE -even in the domain segment of your redirection URL. See my comments in example code below to see an illustration of this through examples of what will work and what will fail.

  2. If a URL (as opposed to a URN (To understand the difference, see here)) is provided in the redirection -for example: if the redirection commences with 'http://', then the redirection link is treated as an ABSOLUTE path.

    Otherwise your redirection link will be treated as a relative link.

  3. If the redirection URI commences with a forward slash character '/', your application server is instructed to construct a URL RELATIVE to the web container!

    For example: relative to localhost:8080

    So the command...

    response.sendRedirect("/foo/stuff.htm")

    from inside a servlet, or

    <a href="/foo/stuff.htm">Stuff page</a>

    from inside a JSP, will take you to

    localhost:8080/foo/stuff.htm.

  4. The ABSENCE of a forward slash at the beginning of your redirection-URL (together with the absence of a protocol signature) will instruct the app server to construct its URL relative to the ORIGINAL REQUESTED URL! That is, the URL typed into the browser by a user at the client-side.

    It is important to be aware that this constructed URL is neither

    • relative to the domain

      nor

    • relative to the web container!

    Once again: the URL constructed by the application server will be relative to the original URL requested by the client!

    So for example: if a client submits the URL

    http://www.example.com/level1/level2/stuff.htm

    then the command...

    response.sendRedirect("foo/stuff.htm")

    from within a servlet or,

    <a href="foo/stuff.htm">Stuff page</a>

    from within a JSP, will redirect you to

    http://www.example.com/level1/level2/foo/stuff.htm

    
    
    

    // WILL NOT WORK! Reason: Case sensitivity. response.sendRedirect("/teluskolearnings/login.jsp");

    // WILL WORK! Reason: Case sensitivity. response.sendRedirect("/TeluskoLearnings/login.jsp");

    // Will redirect to localhost:8080/login.jsp as the forward slash tells app // server to build the URL RELATIVE TO THE APP SERVER. // So you will be pointed to 'http://localhost:8080/login.jsp'. // This is not what we want. response.sendRedirect("/login.jsp");

    // Will redirect to localhost:8080/TeluskoLearnings/login.jsp // as the ABSENCE of forward slash tells app server to build the URL // RELATIVE TO THE URL! // So you will be pointed to // 'http://localhost:8080/TeluskoLearnings/login.jsp'. // This IS what we want. response.sendRedirect("login.jsp");

    // Will redirect to localhost:8080/TeluskoLearnings/foo/login.jsp // (you can see the redirection in the address bar, even if you get a // 404 - page not found) as the ABSENCE of forward slash (at the start) tells // app server to build the url RELATIVE TO THE REQUESTED URL! // This also means that if the user entered // 'http://localhost:8080/TeluskoLearnings/level1/level2/stuff"' // he will be pointed to // 'http://localhost:8080/TeluskoLearnings/level1/level2/foo/login.jsp' // (provided of course, that "/level1/level2/stuff" is captured inside the // urlPatterns parameter of the @WebServlet() annotation). response.sendRedirect("foo/login.jsp");

SEE: https://www.safaribooksonline.com/library/view/head-first-servlets/9780596516680/ch04s27.html

IqbalHamid
  • 2,324
  • 1
  • 18
  • 24