Myroslav Tedoski
Myroslav Tedoski

Reputation: 301

How to keep original JSP in URL after submitting form to a servlet?

I have a data.jsp with form and a servlet (/myservlet) that process that form and return results back to data.jsp

Servlet contains this part:

String redir = "/data.jsp";    
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(redir);
rd.forward(request,response);
return;

Is there any way to retain JSP in the URL instead of servelt? For example,

http://example.com/data.jsp after form submission URL changes to the following while the JSP content is loaded: http://example.com/myservlet

Is it possible to keep data.jsp in URL all the time, so that myservlet will not appear in URL at all?

Upvotes: 1

Views: 2994

Answers (2)

Jafar Ali
Jafar Ali

Reputation: 1114

By what you have mentioned it is a best bet to use ajax. Make a AJAX call on form submittion. submit data to the above servlet and return the desired data. Handle this response on your page.

For the browser. freeze all the form field on submission and show a modal waiting gif. remove the gif on ajax response event and show the response data.

Upvotes: 0

David Levesque
David Levesque

Reputation: 22441

You can do a redirect instead of a forward:

response.sendRedirect("data.jsp");

If you need to use an absolute path, keep in mind that with this method a path starting with / is relative to the server root, not the webapp root, so you need to prepend the context path, e.g.:

response.sendRedirect(request.getContextPath() + "/data.jsp");

Edit: If you want to keep the same URL before and after you submit the form without losing the submitted values, it would be easier to do it the other way around and always call your servlet first in the URL, and then forward to the JSP.

To determine whether you are in "submit" mode or just in "display" mode (blank form), you can check the presence of the submit button as a parameter, e.g.:

if (request.getParameter("mySaveButton") != null) {
    // Process the submitted form values
    ...
}

This is actually the basis of the model-view-controller pattern, where the servlet acts as the controller and the JSP acts as the view. The controller is always called first and forwards the request to the appropriate view or JSP.

Upvotes: 2

Related Questions