Getting response from servlet. ExtJs - java

I have a extJs form with fileupload and servlet. After uploading file i want to get response from servlet.
i do this System.out.println("{success:true, error:'error'}");
But in firebug in POST i dont see anything. This code works in case wiht jsp but not servlet. So how to send parametrs from servlet?

System.out PrintStream is not the the output stream of your servlet response. It is still the "standard" system out stream. Most application servers redirect that to a log file.
Servlet's service() method, as well as do*() methods of HttpServlet, take ServletResponse respectively HttpServletResponse as a parameter. When implementing a servlet, one can call getWriter() on that parameter to get a PrintWriter open on response's output stream. That can be used to print something to the response.
So, your code should be something like:
response.getWriter().println("{success:true, error:'error'}");

Related

Can doGET() receive other arguments than request, response?

I am building a GWT servlet that receives a hashmap and creates excel file from data, converts to byte array and then sends back to client. Can I send my hashmap to my doGet method?
I solved it by calling my exportToExcel server-side code as before, and then in my onSucces I set a window open for my http servlet.

JSP Page Forward Output Includes content from previous form

The problem is: I have a page1.jsp which is submitted and forwarded to page2.jsp. The problem is that the forwarded output should be only the content in page2.jsp, instead of that is showing me content from page1.jsp and immediately the content from page2.jsp
I'm using requestDispatcher.forward(String) but i don know why is this happening
PS: I'm using JE 1.4
Well it seems you have got the method signature incorrect . As per the javaee 1.4 API:
public void forward(ServletRequest request,ServletResponse response)
throws ServletException,
java.io.IOException
Hence your code should be :
RequestDispatcher dispatcher = request.getRequestDispatcher("page2.jsp);
dispatcher.forward( request, response );
Better , you can use the <jsp:forward> standard action.
The JSP that contains the action stops processing, clears its buffer, and forwards the request to the target resource. Note that the calling JSP should not write anything to the response prior to the action.
Suggested Reading:
How to avoid Java Code in JSP-Files?

http get from jsp and resolve status code

I need to send http request to certain URL via jsp (by clicking on a link / button). Depending on the http response status code I need to generate corresponding output in the jsp (200 - action OK, 404 - unknown action etc, the content of the URL is irrelevant). Is there any way to achieve this behaviour?
I am using Spring.
First send your request to a servlet using AJAX and call the url that you want from the servlet.From that url response you can use int status = response.getStatus(); on the HttpServletResponse object in your servlet and based on the int value that you get you can write your if else statements and use PrintWriter's println method to send response/text to the ajax call on your jsp and use it wherever you want in that jsp page.
you can use jquery and make an ajax call using its ajax method and use it success/error callback methods to get textStatus

Java Servlet Behaviour Question

I am currently implementing an OpenID Relying Party (RP) and Identity Provider (IdP) with Java HttpServlets using the OpenID4Java library. I have run into trouble getting two servlets to communicate with each other. I believe the problem I am having is to do more with how Servlets behave, however I have included info about my application for a better sense as to what is happening.
The scenario is as follows:
Servlet #1 (my RP) sends a request to Servlet #2 (my IdP) as follows:
httpResp.sendRedirect(authReq.getDestinationUrl(true));
Essentially authReq = a message with various OpenID specific parameters. By invoking getDestinationUrl(true) it encodes the request into a url to send via a GET.
Servlet #2 catches the above GET in its doGet method. It parses the information, and crafts a reply to send back to Servlet #1 in the following fashion:
String responseText = processRequest(httpReq, httpResp);
httpResp.setContentType("text/html");
OutputStream outputStream = httpResp.getOutputStream();
//
outputStream.write(responseText.getBytes());
outputStream.close();
My problem is, this response never makes it back to Servlet #1. I would expect that when Server #1 receives the response from Servlet #2 that its' doGet or doPost method would catch the message. However neither case happens.
Any advice would be greatly appreciated.
Thanks!
The response of 2nd servlet will directly go on client side i think because its is the original client right? Your 1st servlet is just redirecting the request.
So, if you want to communicate between servlets, Use URLConnection or Apache HttpClient to communicate with 2nd servlet.
You can also make JSP instead of 2nd servlet, then pass you data from 1st servlet to that JSP. That JSP's response will be sent to client then. After all you can do all logic in JSP what you can in servlet.
Hope this helps.
parth.
If you want two servlets to communicate with each other within an application, you can use the ServletContext object and share data via ServletContext.setAttribute and ServletContext.getAttribute and RequestDispatcher obtained via HttServletRequest or ServletContext
In your case can the Servlet#2 be invoked directly by the client? If not then you should probably refactor the processRequest(request, response) into a Utility class or a library. Which in turn can be called by both Servlet#1 and Servlete#2.
response.sendRedirect sends a redirect (301 moved permenently, ithink) to the browser. So your servlet actually sends a response to browser with 301 and then browser makes a request to servlet#2 again.
You can use RequestDispatcher to include your second servlet's response. In this way, the control returns to the first servlet after the method completes.
RequestDispatcher dispatcher = request.getRequestDispatcher(authReq.getDestinationUrl(true));
dispatcher.include(request, response);
However, with this, the response generated by the called servlet will be sent to the browser. If you want your calling servlet to capture the message from called servlet without sending to browser, you can either create a response wrapper (A wrapper writing the contents in a string) and pass this wrapper when you include the second servlet or better you can share the data in either of the scopes (Preferably 'request' scope): You can set the data in the request scope in called servlet and you can retrieve it in the calling servlet after include() completes.
When you redirect, you are telling the browser to make a new request for the URL. So there will be new request/response objects created as if you had clicked on a link in your page.
Hope this helps.

How to handle exceptions from an image-generating Servlet?

I have a simple (Servlet, JSP, and JSTL) web app whose main functionality is displaying images retrieved from a back-end server. The controller servlet forwards the user to a JSP that in turn uses another Servlet to display the resulting image on that same JSP. Further down, the JSP has a line similar to:
<img src="<c:out value='${imageURL}'/>" alt="image view" border="1">
which invokes a GET request on the image-generating servlet causing it to generate the image.
My question is: how do I handle Exceptions thrown by this image-generating servlet?
I already have an error page defined (in web.xml) to handle ServletException within my web app but this doesn't work for this image-generating Servlet, and results in the following errors showing up in my Tomcat server logs:
SEVERE: Exception Processing ErrorPage[exceptionType=javax.servlet.ServletException, location=/WEB-INF/ExceptionPage.jsp]
java.lang.IllegalStateException: Cannot reset buffer after response has been committed
What's my recourse in this situation?
I'd like to be able to handle Exceptions thrown from this image-generating Servlet, and display some error on the main UI or forward the user to another error page.
You can't change the response to redirect to an error page while sending the response. It's already too late to change the entire response then. You can't ask those already sent bytes back from the client side. That's what the IllegalStateException stands for here. It's a point of no return.
Best what you can do is to just log the exception, or to rewrite the code so that it doesn't write any bit to the response (also not setting the response headers) while the business logic hasn't finished its task yet. Once you've determined that the business logic didn't throw any exception, then start writing (and thus indirectly also committing) the response. If the business logic has thrown an exception while the response isn't touched yet, then you can just safely throw it through so that it ends up in an error page. Although in case of an image servlet, you may also want to stream some standard 404.gif to the response instead. This because you can't display another HTML (error) page in an <img> element and you also can't change the URL of the parent JSP/HTML page as well since that concerns a different request.
According to the servlet API no servlet should call the getWriter() and getOutputStream() on the same response object as it causes the IllegalStateException. Usually this is the source of this exception. If you're outputing binary data like and image file you should use getOutputStream().
Looks like the problem you have is within your ExceptionPage.jsp, not your servlet code.
And this
java.lang.IllegalStateException:
Cannot reset buffer after response has
been committed
Means that you've already have tried to send a response.
Probably you've opened an output stream directly and wrote some data to it. Once you've done it you cannot try to set headers and such on a response ( they are already on their way to the client ).
You need to do a better state management. Best way to do this is to separate request preprocessing from the response generation. Once you are writing response, you can only do or die. For this, check that you are not catching IOExceptions from the response output, wrapping them to ServletException and redirect them to your error page. You really cannot handle them in the context of the current request.
First, identify why the Illegal State exception is being thrown. Rather than dealing with a thrown exception, you probably just want to fix your code so that it goes away.
You should catch the exception and forward the request using RequestDispatcher to the required page:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// The following piece of code results in NumberFormatException which will
// be detected by the container. The RequestDispatcher object will forward
// the same request to the other resource, here the file: forwardedJSP.jsp
try {
int test = Integer.parseInt("abc");
} catch (NumberFormatException nfe) {
RequestDispatcher rd = request.getRequestDispatcher("/forwardedJSP.jsp");
rd.forward(request, response);
}}

Categories