Equivalent to Spring MVC @ResponseStatus (HttpStatus.CREATED) in Jersey?

What is the jersey equivalent of this Spring MVC code? I need an answer to return 201 along with the resource URL after a successful POST:

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
Widget create(@RequestBody @Valid Widget wid) {
  return service.create(wid);
}

This is the shortest example I found in Jersey. Is a manual response required for a successful POST / 201?

@POST @Path("widget")
Response create(@RequestBody @Valid Widget wid) {
   return Response
             .status(Response.Status.CREATED)
             .entity("new widget created")
             .header("Location","http://localhost:7001/widget"+wid)
             .build();
  }
+4
source share
2 answers

An example comment for an OP request:

, , . . Response.created(...), . URI String . UriInfo to getAbsolutePathBuilder(), . , .

@Path("/widgets")
public class WidgetResource {

    @Inject
    WidgetService widgetService;

    @POST
    @Consumes(...)
    public Response createWidget(@Context UriInfo uriInfo, Widget widget) {
        Widget created = widgetService.createWidget(widget);

        UriBuilder builder = uriInfo.getAbsolutePathBuilder();
        URI uri = builder.path(created.getId()).build();

        return Response.created(uri).build();
    }
}

, . , uriInfo.getAbsolutePath(Builder), . , http://blah.com/widgets, id - someId, Location: http://blah.com/widgets/someId ( ), 201 Created

Response.created(..) Response.ResponseBuilder, Response.status, . Response , , ok, noContent. API. .

+2

, . .

, - @NameBinding:

@NameBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ResponseStatusCreated {}

, .

@ResponseStatusCreated
@Provider
class StatusCreatedFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, 
                       ContainerResponseContext responseContext) throws IOException {
        responseContext.setStatusInfo(Response.Status.CREATED)

        String location = "..."; // set based on responseContext.getEntity() 
                                 // or any other properties
        responseContext.getHeaders().putSingle("Location", location);
    }
}

.

@POST
@Path("widget")
@ResponseStatusCreated
Object create(@RequestBody @Valid Widget wid) {
    return ... // return whatever you need to build the
               // correct header fields in the filter
}

, , , .. @ResponseStatus(Status.CREATED) , responseContext.getAnnotations().

+2

All Articles