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:
generate Excel .xls (DONE)
write the excel to stream
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..
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.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With