2

I have a Rest Get api:

@GET
@Path("myEndpoint")
public Response getSomething(@Context HttpServletResponse response) {
  // do something with httpServletResponse

}

How do I return the updated HttpServletResponse as javax.ws.rs.core.Response?

Vicky
  • 16,679
  • 54
  • 139
  • 232
  • Just by pasting the Title of that Q in google you will find a lot of info and why @BackSlash answer covers the question... – dbl Feb 13 '19 at 09:08
  • shouldn't the GET method take `HttpServletRequest` instead of `...Response` ? – Ruslan Feb 13 '19 at 09:32
  • @Ruslan there are some cases where you would like to capture the response there. Like for instance reset the responce, override with your custom Content type (headers/body) manually and return it again. Let's say like old school way of a "report file" download. [Check this out](https://stackoverflow.com/questions/21378773/create-and-download-csv-file-javaservlet). Request is not used in the accepted answer and could be omitted. – dbl Feb 13 '19 at 09:52
  • Did my answer help or did I misunderstand your question? – Ori Marko Feb 14 '19 at 06:13
  • @user7294900: I think my question was not clear. I wanted to add some cookies in my Response. But not NewCookie cookies, but http Cookies. So after grabbing HttpServletResponse and adding cookies into it, how do I return that response? That was the doubt. I solved it differently though.. as in with NewCookie. So nevermind! thanks for the response though! – Vicky Feb 14 '19 at 06:23

2 Answers2

0

You can update HttpServletRequest by adding it with @Context in class

@Context
private HttpServletRequest request;

And check it in method

 // do something with httpServletResponse
 checkRequest(request);
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

Expanding a bit on @BlackSlash answer, a better syntax would be:

Response.status(Response.Status.OK).entity(any object here).build();
Or another example:
Response.status(Response.Status.BAD_REQUEST).entity("Error message...").build();

Just remember to set the media type correctly for example:

@Produces(MediaType.APPLICATION_JSON)
Alon
  • 51
  • 1
  • 9