Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set response header in JAX-RS so that user sees download popup for Excel?

I wrote code that generate Excel file using REST JAX-RS and I confirmed that the generated Excel file is in GlassFish server directory.

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. generate Excel .xls (DONE)

  2. write the excel to stream

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

    String fileName = "Blah_Report.xls"; response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

My question is I'm doing all of this in JAX-RS file and I don't have HttpServletResponse object available.

According to the answer from Add Response Header to JAX-RS Webservice

He says:

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..

like image 963
Meow Avatar asked Jan 07 '11 01:01

Meow


People also ask

Can we set response header?

You can set response headers, you can add response headers But think about it for a second, then do this exercise. Draw a line from the HttpResponse method to the method's behavior. We did the most obvious one for you. Pretty obvious when you see them all together.


1 Answers

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() 

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   } } 
like image 165
Tarlog Avatar answered Sep 22 '22 12:09

Tarlog