Is it possible to display a java object(by pointing it in iframe src) obtained from a servlet(In a jsp page) in an Iframe?
Here is what I've tried. I'm storing a pdf file in mysql database as blob type. In the Hibernate bean class I have declared the corresponding variable as Byte[].
Now I'm trying to display the object through Iframe like this.
<% String oid = null;
oid = request.getAttribute("oid").toString();
request.setAttribute("oid",oid);
%>
<js开发者_C百科p:useBean id="cusBean" class="com.zoran.action.CustomBean" scope="page" >
<jsp:setProperty name="cusBean" property="parentId" value="1" />
<jsp:setProperty name="cusBean" property="parentType" value="FILE" />
</jsp:useBean>
<iframe id="displayFrame" src="<%= cusBean.getFile() %>" width="1000" height="500" FRAMEBORDER="0" value="1"></iframe>
And custom bean is the java class where I'm running the hql script to return the blob data through cusBean.getFile().
Am I right in doing this? how else can I print a java object variable in an Iframe.
Please help me out on this.
Thanks, Aditya
Using EL (Expression Language).
<iframe src="${cusBean.file}">
JSP coding rule #1: scriptlets are bad. Never use them. Always use Taglibs/EL. If you ever feel the need to write a scriptlet because it's not possible with Taglibs/EL, then the desired code logic simply belongs in a Java class (servlet, bean, filter, dao, etc) and not in a JSP file.
[Edit] as a response to your first comment: the "Resource not available" error message simply means that the URL is plain wrong. Looking at the actual value %5BLjava.lang.Byte;@967e8c
it look like you're trying to use the String.valueOf(aByteArray)
as URL. This makes no sense. If the ${cusBean.file} actually represents the file contents in flavor of a byte[]
(and thus not the file URL), then you need a servlet which does the reading/writing task. All it basically need to do is the following in the doGet():
// Init servlet response.
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline; filename=\"yourname.pdf\"");
// Init streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Preferably use InputStream, not byte[] as it is memory hogging.
input = new BufferedInputStream(getPdfAsInputStream());
output = new BufferedOutputStream(response.getOutputStream());
// Write file contents to response.
byte[] buffer = new byte[8192];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
close(output);
close(input);
}
Map this servlet in web.xml and call it in the 'src' attribute of your <iframe>
element. If necessary you can also pass a parameter or pathinfo so that the servlet knows what PDF file exactly it needs to read into an InputStream. For example
<iframe src="pdfservlet/${cusBean.fileName}">
and then get the filename as follows:
String fileName = request.getPathInfo();
For more hints you may find this article useful.
Hope this helps.
精彩评论