|
Part:
1
2
3
4
5
6
7
(Continued from previous part...)
Another way of sending non-HTML data to the client is via attachment. The following
JSP will show you how to do this:
<?xml version="1.0"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- Download.jsp
Copyright (c) 2002 by Dr. Herong Yang
-->
<jsp:directive.page session="false" import="java.io.*" />
<jsp:scriptlet>
String p = request.getQueryString();
boolean ok = true;
ok = p!=null;
if (ok) {
if (p.indexOf(".html")>-1) {
response.setContentType("text/html");
} else if (p.indexOf(".gif")>-1) {
response.setContentType("image/gif");
} else if (p.indexOf(".pdf")>-1) {
response.setContentType("application/pdf");
} else if (p.indexOf(".doc")>-1) {
response.setContentType("application/msword");
} else {
ok = false;
}
}
if (ok) {
response.setHeader("Content-disposition",
"attachment; filename="+p);
try {
int l = (int) new File(p).length();
response.setContentLength(l);
byte[] b = new byte[l];
FileInputStream f = new FileInputStream(p);
f.read(b);
ServletOutputStream o = response.getOutputStream();
o.write(b,0,l);
o.flush();
o.close();
f.close();
} catch (Exception e) {
ok = false;
}
}
if (!ok) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
</jsp:scriptlet>
</jsp:root>
In this page, anther header line, "Content-disposition", is added to the response,
in which I am telling the client program that the entity data is an attachment,
with file name specified.
Now try to use IE to request: http://localhost:8080/Download.jsp?hello.pdf, you
will see IE prompting you to save the attachment instead of calling Adobe Reader
to display the data.
IE 6.0 Bug on Display PDF Data
While I was trying to display PDF data, I found that IE 6.0 is not responding
correctly to Content-Type: application/pdf. Here is a sample JSP, GetPdf.jsp,
to show the problem.
<?xml version="1.0"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<!-- GetPdf.jsp
Copyright (c) 2002 by Dr. Herong Yang
-->
<jsp:directive.page session="false" import="java.io.*" />
<jsp:scriptlet>
String p = "hello.pdf";
response.setContentType("application/pdf");
try {
int l = (int) new File(p).length();
response.setContentLength(l);
byte[] b = new byte[l];
FileInputStream f = new FileInputStream(p);
f.read(b);
ServletOutputStream o = response.getOutputStream();
o.write(b,0,l);
o.flush();
o.close();
f.close();
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
</jsp:scriptlet>
</jsp:root>
If you use IE 6.0 to request: http://localhost:8080/GetPdf.jsp, you will
get nothing on the IE window.
Now if you use IE 6.0 to request: http://localhost:8080/GetPdf.jsp?x.pdf, you will
see Adobe Reader displaying the hello message.
Interestingly, if you use IE 6.0 to request: http://localhost:8080/GetPdf.jsp?x.doc,
you will also see Adobe Reader displaying the hello message.
I guess IE 6.0 has a stupid bug. What do you think?
Part:
1
2
3
4
5
6
7
|