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