简体   繁体   English

HttpServletResponse 到 javax.ws.rs.core.Response

[英]HttpServletResponse to javax.ws.rs.core.Response

I have a Rest Get api:我有一个 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 ?如何将更新后的HttpServletResponse作为javax.ws.rs.core.Response返回?

You don't, you have build a Response and return that one: 您没有,您已经建立了一个Response并返回该Response

return Response.ok(entityYouWantToReturn).build();

Example: 例:

@GET
@Path("myEndpoint")
public Response getSomething(@Context HttpServletResponse response) {
    return Response.ok("it worked!").build();
}

This will result in a 200 OK response with body it worked! 这将对it worked!身体产生200 OK响应it worked! . You can use @Produces and @Consumes to make your API accept and/or return different datatypes (application/json etc). 您可以使用@Produces@Consumes来使您的API接受和/或返回不同的数据类型(application / json等)。

You can update HttpServletRequest by adding it with @Context in class 您可以通过在类中添加@Context来更新HttpServletRequest

@Context
private HttpServletRequest request;

And check it in method 并检查方法

 // do something with httpServletResponse
 checkRequest(request);

Expanding a bit on @BlackSlash answer, a better syntax would be: 扩展@BlackSlash答案,更好的语法是:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM