問(wèn)題描述
我編寫(xiě)了使用 REST JAX-RS 生成 Excel 文件的代碼,并確認(rèn)生成的 Excel 文件位于 GlassFish 服務(wù)器目錄中.
I wrote code that generate Excel file using REST JAX-RS and I confirmed that the generated Excel file is in GlassFish server directory.
但我的目標(biāo)是當(dāng)用戶(hù)單擊按鈕(生成 Excel .xls)時(shí),我希望顯示下載彈出窗口,詢(xún)問(wèn)用戶(hù)是保存還是打開(kāi) .xls 文件,就像任何其他用于下載任何類(lèi)型的 Web 服務(wù)一樣文件.
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.
根據(jù)我的搜索,步驟是:
According to my search, the step is:
生成 Excel .xls(完成)
generate Excel .xls (DONE)
將excel寫(xiě)入流
在 JAX-RS 文件中,將響應(yīng)頭設(shè)置為類(lèi)似,
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);
我的問(wèn)題是我在 JAX-RS 文件中執(zhí)行所有這些操作,但我沒(méi)有可用的 HttpServletResponse 對(duì)象.
My question is I'm doing all of this in JAX-RS file and I don't have HttpServletResponse object available.
根據(jù)來(lái)自的回答將響應(yīng)標(biāo)頭添加到 JAX-RS Web 服務(wù)
他說(shuō):
您可以注入對(duì)實(shí)際的 HttpServletResponse 通過(guò)Web 服務(wù)中的 @Context 注釋并使用 addHeader() 等添加您的標(biāo)題.
You can inject a reference to the actual HttpServletResponse via the @Context annotation in your webservice and use addHeader() etc. to add your header.
如果沒(méi)有示例代碼,我真的無(wú)法弄清楚這到底意味著什么..
I can't really figure what exactly that means without sample code..
推薦答案
您不需要 HttpServletResponse 在響應(yīng)上設(shè)置標(biāo)頭.您可以使用javax.ws.rs.core.Response.只需讓您的方法返回響應(yīng)而不是實(shí)體:
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,您可以將其注入到類(lèi)字段之一,或使用屬性或方法參數(shù):
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
}
}
這篇關(guān)于如何在 JAX-RS 中設(shè)置響應(yīng)標(biāo)頭,以便用戶(hù)看到 Excel 的下載彈出窗口?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!