how use RequestDispatcher foward keeping url requested? - java

I have a JSP page to search customers. This page calls the controller, which execute a method to return a list of customers and after forward to the origin URL;
I used to forward : request.getRequestDispatcher(urlOrigin).forward(request, response);
(note 1: request.getHeader("Referer") was used to get complete origin URL )
(note 2: There a method to split the complete origin URL and get name page )
Since it, I have the following url in the browsear :
(http://domain/ProjetoT/mvc)
Its the url of my controller
If I search a customer again won't work, because the controller url will be recognized as origin url.
I Tried use : response.Sendredirect(urlOrigin);
But I lost my object and the list of customers didn't rendered.
Anyone can help me please?
Thanks!

Instead of intially accessing the JSP page directly in the browser, you could access it through the same controller used to process the search. To do that you would have to program your controller to detect if you are in initial display mode or if you are in "submit" mode. This is typically done by checking the presence of a parameter that is sent in the submit.
So in initial display mode, your controller would just forward to the JSP without any further processing, while in submit mode it would do what it is currently doing. This way you would be using the same URL for both the initial display and the submit and the problem you described should go away (that is, if I understand your question correctly).

Related

How to change the url after forwarding a servlet to jsp page?

I have a search.jsp page that has some html content and a form. When the form is submitted, there is a servlet handle the form data and forward the results to the search.jsp page. However, the url in the browser after processing the form is changed to the servlet name:
http://localhost:8080/MyProject/SearchServlet
not the search.jsp page:
http://localhost:8080/MyProject/Search.jsp
How I can change the url to the search.jsp? In other words, I just want to refresh the search.jsp page to display the results in the same page. How I can do that?
You cannot do that by forwarding the request: you need to "tell" the browser to generate a new http request by using the response.sendRedirect() method.
Now the question is why do you want the url bar to display the name of the Jsp?
Hiding the real destination path is a desired feature when forwarding requests: users do not need to know the server side redirects (that's how they are also called) happening in your web app.
Think about it: to carry out its tasks a servlet potentially can forward the request a number of times before getting to the final destination: you don't want the url bar to change each and every single time.
Give a fancier name to your servlet like: "Search" rather than "SearchServlet" so that users will know they are on the search page of your web application and not in the "SearchServlet" page.
In addition to that, if you visit any professional website, you will hardly ever see the .jsp or .html or .php extension on the address bar. While that is not a requirement or specification and you are free to do so, I believe the first approach is best practice (it looks even better to me honestly). There is even a folder WEB-INF whose purpose is to hide your .jsp pages from direct access via url bar.
What I like doing is having a servlet as the landing-welcome page of the web app, that will be responsible to forward and redirect requests based on the user input and the inner working of the application.
Now back to your final request (pun intended)
"In other words, I just want to refresh the search.jsp page to display the results in the same page. How I can do that?"
What I would do is:
redirect the user to the "Search" servlet from the welcome/home servlet.
In the doGet method of the Search servlet I would forward the request to the search.jsp page (you could set attributes before forwarding if you need to).
In the search.jsp I would set the action attribute of the form to "Search" (the name of the servlet) and the method to POST.
In the doPost method of the Search servlet you would implement whatever logic you wish to implement and finally forward the request to the search.jsp
After hitting the search button (and even after the submit button is clicked) what the user will see on the address bar is simply
http://localhost:8080/MyProject/Search
Hope that makes sense.
Are you using the same search.jsp for searching and well as showing the result? It is possible to use the same jsp to perform both the functions but it's easier and desirable to make another jsp which will only show the results.
If you are not able to see the results on search.jsp then make sure that you are setting the proper response in the Servlet class before forwarding it to the jsp and also whether you are reading the response sent by the Servlet class properly in the jsp.
If you want, the page to not refresh at all, then go for AJAX.

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?
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.
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.

Pass parameters from one jsp to another using post method

I want to pass parameters from one jsp to another.
I have tried using the post method, <jsp:forward/>, but it doesn't work.
I have created a <form> in html (parameters passed using POST), which is submitted to a servlet which processes the request and forwards it to another servlet that displays a page.
From this servlet i have created links to another jsp, passing through the parameters as GETs in the URL. However, I actually want to pass the parameters to another jsp using POST, and then pass it on to another jsp.
What solutions do you have or this problem?
Check out the Request Dispatcher. You need to forward the request to the landing JSP.
http://docs.oracle.com/javaee/6/api/javax/servlet/RequestDispatcher.html
Sounds like you are creating a multipage form that gathers information from the user across several distinct pages. In that case one option is to use hidden fields on a form to store the previous values. This of course means that as the pages progress the amount of data passing back and forth from client to server increases.
You may consider a server side approach by storing the interim values in a database for instance, then only passing a token back to the client. When the next JSP page is submitted, use the token to look up the values in the database.
JSP has built-in request object.when one jsp redirect to another jsp with some parameter, you can get parameter value using this request object.
<%
String param1 = request.getParameter("parameter_name");
%>
you can find example here -
http://www.roseindia.net/jsp/RequestObjectInJSP.shtml
Why don't you call a page on the click of a submit button by creating
an url in the below format (in javascript):- var
url="your_page_name.jsp?value1="+encodeURIComponent(document.getElementById("your_text_field_or_any_other_field_id"));
and then call the page by using your url
document.your_form_name.action=url;
document.your_form_name.submit();
and then use request.getParameter() method either in servlet
or in the jsp that u'v metioned in the url (servlet or the jsp u'll be
calling thorugh u'r jsp).

How to change url in user browser without client redirect in servlet

I want to forward from one page to another but with the same I want url to be changed. Suppose user is here http://mywebsite/register and when he completes his registration process then I want this in his address bar http://mywebsite/home
Is it possible without using sendRedirect , I mean by the way server side forwarding only? or any other way around to this problem?
You could just let the HTML form submit to that URL directly.
<form action="http://mywebsite/home">
But this makes no sense. You'll also run into problems when redisplaying the same form with validation messages in case of validation failure. You'd need to redirect back to the original page if you intend to keep the original URL and you'd need to fiddle with storing messages in the session scope instead of the request scope because a redirect basically creates a brand new request. You'll without a redirect also run in "double submit" problem whenever the enduser presses F5 after submitting the form.
Just let the servlet redirect the successful POST request to the desired URL. That's the canonical approach. Even more, this is a recommend "design pattern": the POST-Redirect-GET pattern.
AFAIK there's no way around a redirect since the browser has to update the url at some point. And if you'd update the url after the forwarded to page has been loaded it would issue a refresh and the page would be loaded again (which might result in an endless loop).
Why don't you want to use a redirect in that case?

jsp to servlet communication with parameters from URL, not a form

I'm using netbeans to create a web application that allows a cell phone user to scan a QR code and retrieve a journal's previous/next title information. The take home point is that there's no form that the user will input data into. The QR code will contain the search string at the end of the URL and I want the search to start on page load and output a page with the search results. For now (due to simplicity), my model is simply parsing an XML file of a small sample of MARC records. Oh, to top it off...I'm brand new to programming in java and using netbeans. I have no clue about what javabeans are, or any of the more advance techniques. So, with that background explanation here's my question.
I have created a java class (main method) that parses my xml and retrieves the results correctly. I have an index.jsp with my html in it. Within the index.jsp, I have no problem using get to get the title information from my URL. But I have no clue how I would get those parameters to a servlet that contains my java code. If I manage to get the search string to the servlet, then I have no idea how to send that data back to the index.jsp to display in the browser.
So far every example I've seen has assumed you're getting form data, but I need parameters found, processed and returned on page load...IOW, with no user input.
Thanks for any advice.
Ceci
Just put the necessary preprocessing code in doGet() method of the servlet:
String foo = request.getParameter("foo");
// ...
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
And call the URL of the servlet instead of the JSP one e.g. http://example.com/page?foo=bar instead of http://example.com/page.jsp?foo=bar in combination with a servlet mapping on an URL pattern of /page/*.
You can get the url parameter in servlet using request.getParameter("paramName");
and you can pass the attribute to page from servlet using forwarding request from servlet to jsp.
See Also
Servlet wiki page
Bear in mind that your JSP page will compile internally to a servlet. So you can retrieve the string and print it back in the same JSP. For instance assuming you get the string in a parameter called param you would have something like this in your JSP:
<%
String param = request.getParameter( "param" );
out.println( "String passed in was " + param );
%>
One last thing, you mentioned the main method -- that only gets executed for stand alone applications -- whereas you're talking web/JSP :O

Categories