How to send byte[] as pdf to browser in java web application? - java

In action method (JSF) i have something like below:
public String getFile() {
byte[] pdfData = ...
// how to return byte[] as file to web browser user ?
}
How to send byte[] as pdf to browser ?

In the action method you can obtain the HTTP servlet response from under the JSF hoods by ExternalContext#getResponse(). Then you need to set at least the HTTP Content-Type header to application/pdf and the HTTP Content-Disposition header to attachment (when you want to pop a Save As dialogue) or to inline (when you want to let the webbrowser handle the display itself). Finally, you need to ensure that you call FacesContext#responseComplete() afterwards to avoid IllegalStateExceptions flying around.
Kickoff example:
public void download() throws IOException {
// Prepare.
byte[] pdfData = getItSomehow();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
// Initialize response.
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType("application/pdf"); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setHeader("Content-disposition", "attachment; filename=\"name.pdf\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead.
// Write file to response.
OutputStream output = response.getOutputStream();
output.write(pdfData);
output.close();
// Inform JSF to not take the response in hands.
facesContext.responseComplete(); // Important! Else JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
That said, if you have the possibility to get the PDF content as an InputStream rather than a byte[], I would recommend to use that instead to save the webapp from memory hogs. You then just write it in the well-known InputStream-OutputStream loop the usual Java IO way.

You just have to set the mime type to application/x-pdf into your response. You can use the setContentType(String contentType) method to do this in the servlet case.
In JSF/JSP you could use this, before writing your response:
<%# page contentType="application/x-pdf" %>
and response.write(yourPDFDataAsBytes()); to write your data.
But I really advise you to use servlets in this case. JSF is used to render HTML views, not PDF or binary files.
With servlets you can use this :
public MyPdfServlet extends HttpServlet {
protected doGet(HttpServletRequest req, HttpServletResponse resp){
OutputStream os = resp.getOutputStream();
resp.setContentType("Application/x-pdf");
os.write(yourMethodToGetPdfAsByteArray());
}
}
Resources :
mimeapplication.net - pdf
Javadoc - ServletResponse
Javadoc - HttpServlet

When sending raw data to the browser using JSF, you need to extract the HttpServletResponse from the FacesContext.
Using the HttpServletResponse, you can send raw data to the browser using the standard IO API.
Here is a code sample:
public String getFile() {
byte[] pdfData = ...
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
OutputStream out = response.getOutputStream();
// Send data to out (ie, out.write(pdfData)).
}
Also, here are some other things you might want to consider:
Set the content type in the HttpServletResponse to inform the browser you're sending PDF data:
response.setContentType("application/pdf");
Inform the FacesContext that you sent data directly to the user, using the context.responseComplete() method. This prevents JSF from performing additional processing that is unnecessary.

Related

Send data in the doPost() response?

I am a complete beginner in web programming. I created an application with Eclipse Java EE and a Tomcat server running in localhost.
The goal of the application is to get information from a client and send back other information.
I developped a servlet and implement a doPost() method that works perfectly. I get information that I saved in a bean named USSDPull and write in a text file named log.txt.
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
USSDPull ussdpull = new USSDPull();
ussdpull.setUssdstring(request.getParameter("ussdstring"));
ussdpull.setSessionid(Integer.parseInt(request.getParameter("sessionid")));
ussdpull.setMsisdn(request.getParameter("msisdn"));
ussdpull.setUssdcode(request.getParameter("ussdcode"));
ussdpull.setEncoding(Integer.parseInt(request.getParameter("encoding")));
response.setContentType("text/text");
response.setCharacterEncoding( "UTF-8" );
PrintWriter out = response.getWriter();
out.flush();
out.println("POST received : " + ussdpull.getUssdstring()+" "+ussdpull.getSessionid()+" "+ussdpull.getMsisdn()+" "+ussdpull.getUssdcode()+" "+ussdpull.getEncoding());
//WRITE IN FILE
FileWriter fw = new FileWriter("D:/Users/Username/Documents/log.txt", true);
BufferedWriter output = new BufferedWriter(fw);
output.write(dateFormat.format(date)+";"+ussdpull.getUssdstring()+";"+ussdpull.getSessionid()+";"+ussdpull.getMsisdn()+";"+ussdpull.getUssdcode()+";"+ussdpull.getEncoding()+"\n");
output.flush();
output.close();
}
I need the servlet to send back 2 specific booleans and 1 string to the client. I don't know how to proceed. Is it possible to use the HttpServletResponse to send the data? Or do I need to find a way to "call" the doGet() method?
The HttpServletResponse itself doesn't give you a way to write data back to the client other than some headers, such as the response code.
However, it has a method called getOutputStream and a method getWriter() that give you resp. an OutputStream or a PrintWriter. You can use these to write data to the response.

Struts 1 Action Return Success After Downloading a Binary File

I know how to download a binary file from my web app by setting the response header and copying the binary file to the response's outputstream. But what I'm having trouble with is returning success so the page will reload. If I return success I will get the error:
java.lang.IllegalStateException: getOutputStream() has already been
called for this response
See the below code example. This will download the file and then throw the exception. Is there a way to restore the response?
public ActionForward export(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//tell browser program going to return an application file
//instead of html page
response.setContentType("application/force-download");
response.setHeader("Content-Disposition","attachment;filename=temp.csv");
IOUtils.copy(new FileInputStream("/path to some file"), response.getOutputStream());
response.flushBuffer();
return mapping.findForward("success");
}
I don't believe you can do a redirect or reload after a file download. This is more of an HTTP restriction, not something specific to Struts 1.
It takes one HTTP response to download a file to a browser, and one HTTP response to reload the page. You are attempting to do both from the same HTTP request, which simply isn't possible. A request cannot have more than one response.
In much the same way, you can't issue a redirect after you've served a page to the user, unless the page itself contains a <meta refresh="..."> element or some JavaScript that does a reload. Both approaches essentially create another HTTP request, but neither approach is open to you because it's not possible to do either with a file download.
In short, it's not possible to do what you are asking for.
You can set response.setHeader("Refresh", "1"); according to this article:
http://users.polytech.unice.fr/~buffa/cours/internet/POLYS/servlets/Servlet-Tutorial-Response-Headers.html
But it doesn't work when you close browser file download popup.

Setting Response Headers of HTTPServeletResponse

So, I am constructing a URL from values from a database. Now, I want to make sure that the response headers are what I specify for this URL. How do I achieve this?
For instance, if I construct a URL such as www.google.com/username=ak&password=bk, I want to make sure that the connection is keep alive for the response that you get when you hit the URL. How do I do this within JSP/Java?
The reason being, I'm trying to render a video on an iOS device from my CMS however this doesn't work and from what I have read, the response headers must be set. How do I set response headers for a URL that I might hit?
The following method is how I am setting the response however the response is not the url I make. The URL I make is something like www.uisghsfgsgsfg.com/cs/sksjdgs/appl. I am confused as to what the response means in the context of this page.
class URLConstructor extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Connection", "Keep-Alive");
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(512);
response.setContentLength(byteStream.size());
response.addHeader("Connection", "Keep-Alive");
}
}
Assumption: You have access to the server which transmits the video.
The code which transmits the video to your client (IOS device) should set the response headers before sending the response(video content). If it is a Java program which serves the request for the video, you can set the appropriate header in the Servlet API (See Martin's link).
Hope that helps.

Response/Request between Javascript/Java Servlet

I have a simple test client-server app. Client is html/javascript, server - Java Servlet
First of all I want to test request/response mechanism. Therefore I have used a simple code for cliet(jQuery):
$.get ("http://localhost:8081/TestProject/BasicServlet",
function(data) {
alert('Data:' +data);
}
);
And on the server side:
protected void doGet(HttpServletRequest req, HttpServletResponse res) ... {
String callBack = "TestCallback";
res.setContentType("text/html");
ServletOutputStream out = res.getOutputStream();
out.write(callBack.getBytes("UTF-8"));
out.flush();
}
So, Servlet catches request from client, but I have a problem with response, response header looks good, with character attributes, but I don't receive the callBack data
As response in Firebug I have 3 tabs, Header, Answer, HTML. Answer and HTML are empty
EDIT:
I have found a Problem: it was Access-Control-Allow-Origin violation.
Thanks for help !
As per the documentation in here
http://download.oracle.com/javaee/6/api/javax/servlet/ServletResponse.html#getOutputStream
is used for sending binary data. So my guess is that Content-Type header is set as some MIME type which is not recognized by jQuery. I suggest you check whether the Content-Type header is still "text/html" in the response using FireBug, or use
PrintWriter writer = res.getWriter();
writer.write(callBack);
writer.flush();
By the way, for sending textual data using PrintWriter is the recommended approach.
Try out.print() instead of out .write() you will get the response in your ajax call.

How to make a servlet interact with the API of a website and also store the XML response?

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "some text";
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(text); // Write response body.
}
If I use this servlet , where request variable will have the url of the API of the website . Then how do I capture the response ? I would want to know what is the code to do that , and is this the right way to go about it when trying to build a JSP page that deals with interacting with an API of a website and showing data ?
You're confusing things. The HttpServletRequest is the HTTP request which the client (the webbrowser) has made to reach the servlet. The HttpServletResponse is the response which you should use to send back the result to the client (the webbrowser).
If you want to fire a HTTP request programmatically, you should use java.net.URLConnection.
URLConnection connection = new URL("http://example.com").openConnection();
InputStream input = connection.getInputStream(); // This contains the response. You need to convert this to String or some bean and then display in JSP.
See also:
How to use java.net.URLConnection to fire and handle HTTP requests

Categories

Resources