Question


I have a login form and a servlet that makes the login. If the user is valid, i redirect him to the next page

response.sendRedirect("welcome.jsp");

Also i want to send an object to this page, so i replace the sendRedirect with this

request.setAttribute("notes", notesObject)
disp = getServletContext().getRequestDispatcher("/welcome.jsp");
disp.forward(request, response);

The problem now is that now, when a user logs in (e.g. user / 111), in the address bar i have this:

localhost:8084/WebApplication2/loginServlet?username=user&password=111&action=LOGIN

but when i used the Sendredirect i had only the localhost:8084/WebApplication2/welcome.jsp

The login Servlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
//code...

The jsp file:

 <form action="loginServlet">
//code...
Was it helpful?

Solution

The issue is not with forward() or sendRedirect(), it's with how you are sending the data from the HTML form.

Remember, the <form> tag uses GET method as default HTTP method. Since you haven't given any method explicitly, it will use GET method.

See this link:

<!ATTLIST FORM
  %attrs;                              -- %coreattrs, %i18n, %events --
  action      %URI;          #REQUIRED -- server-side form handler --
  method      (GET|POST)     GET       -- HTTP method used to submit the form--
  enctype     %ContentType;  "application/x-www-form-urlencoded"
  accept      %ContentTypes; #IMPLIED  -- list of MIME types for file upload --
  name        CDATA          #IMPLIED  -- name of form for scripting --
  onsubmit    %Script;       #IMPLIED  -- the form was submitted --
  onreset     %Script;       #IMPLIED  -- the form was reset --
  accept-charset %Charsets;  #IMPLIED  -- list of supported charsets --
  >

Now, with GET request, all your form data goes as a part of your query string, that is why you are seeing those data there. You should change the method to POST.

<form action="loginServlet" method = "POST">

The reason why you didn't see the data while using sendRedirect() is that, with response.sendRedirect() the client creates and sends a new request. So, your old request URI is no longer there. With forward() this is not the case. The URI doesn't changes, and you see the original URI, with the query string.

when i used the Sendredirect i had only the localhost:8084/WebApplication2/welcome.jsp

As I said, the URI changes, that you can see. Hence you don't see the query string, that came with original URI.

See also:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top