Send response and request from JSP to servlet - java

How can I send my response and request object from a jsp file to a servlet by code? I don't want to submit a form or so.
I tried it with:
response.setRedirect("my page"):
But then it says:
Exception in thread "main" org.apache.http.client.HttpResponseException: Moved Temporarily
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:68)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:54)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:945)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:919)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:910)
at com.xx.xx.client.Client.sendPOSTRequest(Client.java:185)
at com.xx.xx.client.Client.main(Client.java:46)
As clarification: I have a client that sends a post request to a JSP file. This JSP file parses a file and puts the needed information into the session. I want to call a servlet from this jsp file to add something into the database. I think this error code is thrown by this line String responseBody = httpclient.execute(httppost, responseHandler);

You can just use <jsp:include> on a servlet URL.
<jsp:include page="/servletURL" />
The servlet doXxx() method will just be invoked with the current request/response. Note that the servlet cannot forward to another JSP afterwards. It has to write directly to the response, or to set some request/session attributes which the JSP can intercept on after the <jsp:include> line.
Note that this is bad design. You're abusing a JSP as a front controller. It should be the other way round. The servlet should act as a front controller and the JSP should act as a view. The client should send the request to the servlet URL directly instead of to some JSP file. The servlet should perform the business job and finally forward to a JSP to let it present the results in HTML. See also our servlets tag wiki page for some Hello World examples.

you can use the RequestDispatcher forward(ServletRequest request, ServletResponse response)
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
You can do it like this:
ServletContext context= getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("/YourServlet");
rd.forward(request, response);
UPDATE
Also note on your code that you have response.setRedirect instead of response.sendRedirect(...) but note that this method will not work as you want it to because it just asks the browser to make a new request to your servlet rather than forward your request and response object to that servlet . See RequestDispatcher.forward() vs HttpServletResponse.sendRedirect() for more info

Related

How to get the previous request form that returns an object to a Servlet?

[Passing an object from JSP page back to Servlet
From the top reviewed answer of the question above,
What does Form preprocessing Servlet and Form postprocessing Servlet mean? Where do I put it in my servlet? Do I put it on the same method? Do I call preprocessing Servlet first then proceed with the form submission of my JSP file and then proceed to the postprocessing file?
You write both the code in the same servlet in the sequence mentioned below:
A. Get the request parameters from the request (which may have values of HTML form elements and explicit request parameters), as mentioned in the Form postprocessing part
String myObjectId = request.getParameter("myObjectId");
Object myObject = request.getSession().getAttribute(myObjectId);
request.getSession().removeAttribute(myObjectId);
// ...
B. Perform some business logic and forward the request to some JSP, as mentioned in the Form preprocessing part
String myObjectId = UUID.randomUUID().toString();
request.getSession().setAttribute(myObjectId, myObject);
request.setAttribute("myObjectId", myObjectId);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

Why does servlet name stay in url after RequestDispatcher.forward?

I am making a JSP/Servlet web app which starts with log in page.
After user enters log in information, a servlet, called LoginServlet, processes the data and if the log in is successful the servlet redirects user to MainPage.jsp like this:
RequestDispatcher rd = request.getRequestDispatcher("MainPage.jsp");
rd.forward(request,response);
It works. It takes me to MainPage.jsp, only the URL is NOT:
http://localhost:8080/RestauRec/MainPage.jsp
it is:
http://localhost:8080/RestauRec/LoginServlet
It is not an actual problem, but still, I want to know why this is and how can I change this?
Note: I don't know if it matters or not but, in the action attribute of the form element (in the log in page) I place LoginServlet. Like this:
<form action="LoginServlet" method="POST">
Thanks in advance!
forward is an action that happens within a single request-response cycle. It uses the forward-to resource to complete the response.
Your browser sends a single request to /someUrl and your server handles it, returning a response.
It is not an actual problem, but still, I want to know why this is and how can I change this?
You'd have to make your client, the browser, send a different request to another URL, possibly because of a redirect.
forward() method won't change the url. sendRedirect() in HttpServletResponse do change the url as well.
response.sendRedirect("MainPage.jsp");
Remember that a new request gets hit to the container when you do redirect. That means all the previous data vanishes and you'll get a brand new request.

Stop form submit after page refresh with DispatcherServlet

I use request.getRequestDispatcher(url).forward(request, response) method in my controller !! I am in trouble. (I know that dispatcher make internal redirect, a forward reuses the current request), when I fill in a form and send request to controller that computes some logic and after forward to some simple page. If I push F5 in browser on my simple page (refresh page) my request will perform again. How to prevent this situation ??
RequestDispatcher will keep request attributes and forward page with same request, that is why if you refresh page controller gets same request and process it again. Use SendRedirect instead.

Forward request to servlet using jquery which in turn forwards to jsp?

I have a js file and based on the below condition I need to display a message or forward the request to servlet which in turn forwards to jsp.
var isInIframe = (parent !== window),
if (isInIframe) {
//Forward request to servlet
}else {
//Display Access denied message
}
I can call a servlet using jquery ajax. But how can I forward request to servlet? once the request is forwarded to servlet then servlet will load some property files and forwards request to some.jsp as below.
//Keeps some values using request.setAttribute() then forward the request
request.getRequestDispatcher("/WEB-INF/some.jsp").forward(request, response);
How can i do that?
Thanks!
You can use Session for sending some objects to servlet. Because session remains same for the user throughout the application.
JQuery/Javascript does not "forward" requests to web applications. It makes new requests via AJAX or redirects. JQuery itself does not handle HTTP requests.
You need to make an AJAX request for this. I assume that JSP is the presentation layer of your web application. So just make an ajax request to your web app using the JQuery $.ajax() method..
You can handle the response using the AJAX callback function
Servlet and jsp are server-side components. The Server receives HTTP requests and dispatches a Servlet to handle them by producing a corresponding HTTP response for each of them, some times with the help of a jsp.
Javascript is a client-side component. It runs in the browser. When the javascript runs, the HTTP response containing the HTML you see in the browser has already been sent, so the Servlet is completely out of the picture. You cannot forward to it like you are imagining with
request.getRequestDispatcher("/WEB-INF/some.jsp").forward(request, response);
What you can do is use ajax to construct and send a new HTTP request that will be handled by a Servlet.

Go back to same JSP that sent request with RequestDispatcher in Servlet

I have a servlet which can get requests by multiple JSP's.
But when I use the RequestDispatcher in the servlet, I don't know how to forward to the JSP that sent the request.
req.getRequestDispatcher("page.jsp").forward(req, resp);
I know there is something like this in html: javascript:javascript:history.go(-1)
I just need something like this:
req.setAttribute("originalRequest", req.getRequestPage());
req.getRequestDispatcher(originalRequest).forward(req, resp);
That piece of code is probably very noob but it gives you the idea of what I need.
So: I need to forward to the page that sent the original request (basically reload the page), but because multiple jsp's use the servlet, I cannot simply forward to "page.jsp"
You can do following
Create a hidden parameter for every jsp named jspName and give value for respective JSPs. e.g. for JSP A, parameter name is jspName and value is a, for JSP B, parameter name is jspName and value is b
Read this hidden parameter in the servlet using following code.
String jspName = request.getParameter("jspName");
RequestDispatcher rd = request.getRequestDispatcher(jspName);
rd.forward(request, response);
When you are calling the servlet from JSP A, then it will have paramter japName=a, when servlet code is running, it will retrieve the value a from request.getParamter("jspName") and a getRequestDispatcher(jspName) will create the dispatcher for the same and rd.forward(request, response) will forward to the jsp.
I have not tried the following, but I hope this may help you to solve your problem.
req.setAttribute("originalRequest", req.getRequestPage());
req.getRequestDispatcher(req.getAttribute(originalRequest).toString()).forward(req, resp);
I have tried in this way, It's working for me...
In JSP
You need to set this in every JSP. For ex: index.jsp is my jsp name.
<% session.setAttribute("jspName","index.jsp"); %>
In Servlet
request.getRequestDispatcher(session.getAttribute("jspName").toString()).forward(req, res);

Categories

Resources