1

I've got a Java Servlet web application, everything is working great. There's one small thing bothering me, however.

When a person logs in, the form is forwarded to the LoginServlet that verifies the information. When the information has been verified, the user gets redirected to dashboard.jsp. The thing that is bothering me is that the URL in the browser says 'http://localhost:8080/LoginServlet.do' instead of 'http://localhost:8080/dashboard.jsp'. I am forwarding the request and response objects, so I need to use a RequestDispatcher, right?

How can I make sure the URL reads 'dashboard.jsp' instead of 'LoginServlet.do'?

Login Servlet:

public class LoginServlet extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /*
        * Information that has arrived here, has been checked by the login filter.
        * This servlet takes the parameters from the form, calls the UserService and tries to login.
        * If it succeeds: put the User object in the session scope, and redirect to welcome.jsp with a message 'login successful'
        * If it fails: redirect back to index.jsp with a message 'Login failed'
        */

        RequestDispatcher rd;
        String email = req.getParameter("loginEmail");
        String password = req.getParameter("loginPassword");

        UserService us = ServiceProvider.getUserService();
        User u = us.loginUser(email, password);
        if(u != null) {
            // User information was correct, login successful.
            req.getSession().removeAttribute("loggedUser");
            req.getSession().setAttribute("loggedUser", u);
            req.setAttribute("message", "Login successful");
            u.getAllPomodoros();
            rd = req.getRequestDispatcher("dashboard.jsp");
            rd.forward(req, resp);
        } else {
            // Login failed. Redirect to index.jsp
            req.setAttribute("message", "Login failed");
            rd = req.getRequestDispatcher("index.jsp");
            rd.forward(req, resp);
        }
    }
}

My Web.xml (not sure if it's relevant):

--SNIP--
    <servlet>
        <servlet-name>Login Servlet</servlet-name>
        <servlet-class>controller.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Login Servlet</servlet-name>
        <url-pattern>/LoginServlet.do</url-pattern>
    </servlet-mapping>
--SNIP--
Cake
  • 493
  • 7
  • 16

4 Answers4

1

The forward tells the server to use the given JSP to show the result data. There is no interaction with the client here to send a new HTTP request to the JSP. If you are looking at seeing the JSP in the address bar, then you need to tell the client to send a new HTTP request every time. And that would mean you use the send redirect, so it would be

response.sendRedirect(request.getContextPath() + "/index.jsp");
  • Thank you for answering. Could you tell me what the use of `request.getContextPath()` is for? – Cake Jun 12 '16 at 18:03
  • getContextPath() returns the Name of the App as seen in your URl. So if your URL is something like 'http://localhost:8080/App/index.jsp, your context path would be App – Ratnakar Sadasyula Jun 12 '16 at 18:10
  • Gotcha. Do you recommend using that on every link? Thanks for answering. – Cake Jun 12 '16 at 18:11
  • I would really not suggest sendRedirect, it much more slower compared to forward, unless you really have a requirement, where you need to track the JSP – Ratnakar Sadasyula Jun 12 '16 at 18:20
1

You should use response.sendRedirect(URLYouWantThemToBeSentTo) because the forwarding is done on the server and the client/navigator has no clue it happened.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • If I use the sendRedirect, will the Reponse and Request object still be forwarded? Because I rely on my Dashboard.jsp having access to the 'loggedUser' in the session scope. – Cake Jun 12 '16 at 18:02
  • @Cake You don't have to worry if it's in the session scope, as long as it isn't in the request scope it's ok. This does not throw you out of the session. – Yassin Hajaj Jun 12 '16 at 18:08
  • ah that makes sense. The request scope gets destroyer after I use the sendRedirect. What would be the most elegant way of sending a message 'along-side' to the next page (with 'Successfully logged in')? Would I have to put that message in the SessionScope, then display the message and remove the message from the SessionScope again? – Cake Jun 12 '16 at 18:11
  • @Cake You could save the message as a session attribute I guess.. Since you're not using the request anymore. Don't forget to delete the message after it though. Related : http://stackoverflow.com/questions/17001185/pass-hidden-parameters-using-response-sendredirect – Yassin Hajaj Jun 12 '16 at 18:14
1

More Information about sendRedirect()

-New request is created for the destination resource.

-Two request and response calls are consumed.

-We can see redirected address, it is not transparent.

-The sendRedirect() method is slower ( then forward() ) because when new request is created old request object is lost.

-It is declared in HttpServletResponse.

Taha
  • 1,072
  • 2
  • 16
  • 29
  • 1
    Thank you for taking the time to post! Useful information indeed, exactly what I was looking for. – Cake Jun 12 '16 at 18:03
0

I would 'refactor' your solution a little bit:

  • The solution is based on redirects. Why ? Because the component responsible for the authentication has NOT to be hosted on the server where the application is running (most of the time it is not and it is a specialized component).

  • The users opens the dashboard.jsp.

  • A servlet filter is responsible to check if a cookie of authentication is present (making usage of a dedicated software component). If the cookie is not present then the user is redirected to a software component responsible to authenticate the user (looks like your LoginServlet) and the trick is to add &goto=dashboard.jsp (where you come from, the page you want to open).

  • LoginServlet does authenticate the user (any kind of authentication:user name and password, eid, ...). If the authentication is OK then the cookie is created and the user is redirected (using the goto=URL). For example to dashboard.jsp.

  • After the redirection to dashboard.jsp has happened, this time the filter will let you open the dashboard.jsp or any page that is protected by the filter because of the cookie.

That is some way to achieve modern authentication. Of course you can also use frameworks (Spring Security), applications (openAM) to achieve the same. Hope I was clear enough.

Rudy Vissers
  • 5,267
  • 4
  • 35
  • 37