我有一个部署到Apache Tomcat的Spring MVC应用程序。其中一个页面必须显示使用itext pdf库生成的PDF文件。
所以我已经将object
标记添加到JSP文件中:
<object data="<c:url value="/view-pdf" />"></object>
我在控制器内部有处理此URL的方法:
@RequestMapping(value = "/view-pdf", method = RequestMethod.GET)
protected void viewPdf(HttpServletResponse response) {
ServletOutputStream out = response.getOutputStream();
//generate pdf here
Document document = new Document();
PdfWriter.getInstance(document, out);
document.setPageSize(PageSize.A4);
document.open();
document.add(new Paragraph("Hello, World"));
document.close();
out.close();
}
现在,当我打开应该显示PDF的页面时,它不会显示PDF文件。 Chrome控制台显示以下错误:
Refused to display 'http://localhost:8080/MyApp/view-file' in a frame because it set 'X-Frame-Options' to 'deny'.
在地址栏中直接输入http://localhost:8080/MyApp/view-pdf
URL时,可以访问PDF。所以PDF生成没有问题。
此处的一些答案建议将这些行添加到web.xml
文件中:
<filter>
<filter-name>httpHeaderSecurity</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>antiClickJackingEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>antiClickJackingOption</param-name>
<param-value>ALLOW-FROM</param-value>
</init-param>
<init-param>
<param-name>antiClickJackingUri</param-name>
<param-value>http://localhost:8080/MyApp/*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>httpHeaderSecurity</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
我这样做了,但根本没有效果。我在这做错了什么?如何避免这个错误?
我的Spring版本是5.0.4.RELEASE,Tomcat版本是8.0.48。
答案 0 :(得分:2)
问题是Spring安全性中的'X-Frame-Options'响应头。 检查 spring security config - 因为默认情况下出于安全原因设置为拒绝 - 请参阅以下链接以了解要提供的选项。
How to disable 'X-Frame-Options' response header in Spring Security?
答案 1 :(得分:0)
如何将viewPdf方法更改为:
@RequestMapping(value = "/view-pdf", method = RequestMethod.GET)
protected void viewPdf(HttpServletResponse response) {
ServletOutputStream out = response.getOutputStream();
// The next line could fix your problem
response.setHeader("X-Frame-Options", "SAMEORIGIN");
//generate pdf here
Document document = new Document();
PdfWriter.getInstance(document, out);
document.setPageSize(PageSize.A4);
document.open();
document.add(new Paragraph("Hello, World"));
document.close();
out.close();
}