问题描述
我编写了使用 REST JAX-RS 生成 Excel 文件的代码,并确认生成的 Excel 文件位于 GlassFish 服务器目录中.
I wrote code that generate Excel file using REST JAX-RS and I confirmed that the generated Excel file is in GlassFish server directory.
但我的目标是当用户单击按钮(生成 Excel .xls)时,我希望显示下载弹出窗口,询问用户是保存还是打开 .xls 文件,就像任何其他用于下载任何类型的 Web 服务一样文件.
But my goal is when user click on the button (which generate Excel .xls), I want download popup to show up asking user whether to save or open the .xls file just like any other web services doing for downloading any type of files.
根据我的搜索,步骤是:
According to my search, the step is:
生成 Excel .xls(完成)
generate Excel .xls (DONE)
将excel写入流
在 JAX-RS 文件中,将响应头设置为类似,
in JAX-RS file, set response header to something like,
字符串文件名 = "Blah_Report.xls";response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
String fileName = "Blah_Report.xls"; response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
我的问题是我在 JAX-RS 文件中执行所有这些操作,但我没有可用的 HttpServletResponse 对象.
My question is I'm doing all of this in JAX-RS file and I don't have HttpServletResponse object available.
根据来自的回答将响应标头添加到 JAX-RS Web 服务
他说:
您可以注入对实际的 HttpServletResponse 通过Web 服务中的 @Context 注释并使用 addHeader() 等添加您的标题.
You can inject a reference to the actual HttpServletResponse via the @Context annotation in your webservice and use addHeader() etc. to add your header.
如果没有示例代码,我真的无法弄清楚这到底意味着什么..
I can't really figure what exactly that means without sample code..
推荐答案
您不需要 HttpServletResponse 在响应上设置标头.您可以使用javax.ws.rs.core.Response.只需让您的方法返回响应而不是实体:
You don't need HttpServletResponse to set a header on the response. You can do it using javax.ws.rs.core.Response. Just make your method to return Response instead of entity:
return Response.ok(entity).header("Content-Disposition", "attachment; filename="" + fileName + """).build()
如果您仍想使用 HttpServletResponse,您可以将其注入到类字段之一,或使用属性或方法参数:
If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:
@Path("/resource")
class MyResource {
// one way to get HttpServletResponse
@Context
private HttpServletResponse anotherServletResponse;
// another way
Response myMethod(@Context HttpServletResponse servletResponse) {
// ... code
}
}
这篇关于如何在 JAX-RS 中设置响应标头,以便用户看到 Excel 的下载弹出窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!