是否可以在 Iframe 中显示从 servlet(在 jsp 页面中)获取的 java 对象(通过在 iframe src 中指向它)?
这是我尝试过的。 我将 pdf 文件作为 blob 类型存储在 mysql 数据库中。在 Hibernate bean 类中,我已将相应的变量声明为 Byte[]。
现在我尝试像这样通过 Iframe 显示该对象。
<% String oid = null;
oid = request.getAttribute("oid").toString();
request.setAttribute("oid",oid);
%>
<jsp: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().
我这样做对吗?我还能如何在 Iframe 中打印 java 对象变量。
请帮我解决这个问题。
谢谢, 阿迪亚
最佳答案
<iframe src="${cusBean.file}">
JSP 编码规则#1:scriptlet 很糟糕。切勿使用它们。始终使用标签库/EL。如果您觉得需要编写一个 scriptlet,因为 Taglibs/EL 无法实现,那么所需的代码逻辑就属于 Java 类(servlet、bean、filter、dao 等),而不是 JSP 文件。
[编辑]作为对您第一条评论的回应:“资源不可用”错误消息仅意味着 URL 完全错误。查看实际值%5BLjava.lang.Byte;@967e8c
看起来您正在尝试使用 String.valueOf(aByteArray)
作为网址。这毫无意义。如果 ${cusBean.file} 实际上代表 byte[]
风格的文件内容 (因此不是文件 URL),那么您需要一个执行读/写任务的 servlet。它基本上需要做的就是 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);
}
在 web.xml 中映射此 servlet 并在 <iframe>
的 'src' 属性中调用它元素。如果需要,您还可以传递参数或路径信息,以便 servlet 确切地知道需要将哪个 PDF 文件读入 InputStream。例如
<iframe src="pdfservlet/${cusBean.fileName}">
然后获取文件名如下:
String fileName = request.getPathInfo();
有关更多提示,您可以找到this article有用。
希望这有帮助。
关于java - 显示 java 对象时的 iframe 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1679924/