問題描述
我編寫了使用 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 的下載彈出窗口?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!