Cake Cake - 2 years ago 111
Java Question

Java Servlets - Forward to url instead of

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/' 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 ''?

Login Servlet:

public class LoginServlet extends HttpServlet{

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().setAttribute("loggedUser", u);
req.setAttribute("message", "Login successful");
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):

<servlet-name>Login Servlet</servlet-name>

<servlet-name>Login Servlet</servlet-name>

Answer Source

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download