如何在 JAX-RS 中设置响应头,以便用户看到 Excel 的下载弹出窗口? [英] How to set response header in JAX-RS so that user sees download popup for Excel?

查看:28
本文介绍了如何在 JAX-RS 中设置响应头,以便用户看到 Excel 的下载弹出窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了使用 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 文件,就像任何其他网络服务为下载任何类型所做的一样文件.

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:

  1. 生成 Excel .xls(完成)

  1. generate Excel .xls (DONE)

写excel流

在 JAX-RS 文件中,将响应头设置为类似,

in JAX-RS file, set response header to something like,

String fileName = "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 通过网络服务中的 @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.只需让您的方法返回 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 的下载弹出窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆