Java – create a response using the location header in jax-rs

In NetBeans, I automatically generate classes with restful templates from entities and crud functions (annotated with post, get, put and delete) I have a problem with the Create method. After inserting an entity from the front end, I want to create and update a response so that my view will automatically (or asynchronously, if this is the correct term) reflect the added entity

I came across this (example) line of code, but it was written in C # (I didn't know anything about it):

HttpContext.Current.response.addheader("Location","api/tasks" +value.Id);

Using jax-rs in Java, can you still get the current httpcontext and manipulate the header like c#?

What I met recently is

Response.ok(entity).header("Location","api/tasks" + value.Id);

It certainly won't work Before building the response, it seems necessary to get the current httpcontext

Thanks for your help.

Solution

I think you mean to do something like response created(createdURI). Build() This creates a response with 201 created status, and createuri is the location header value This is usually done with posts On the client side, you can call the response that will return the new URI getLocation().

From the response API

> public static Response. Responsebuilder created (URI location) – create a new responsebuilder for the created resource and set the location header with the provided value. > Public abstract URI getlocation() – returns the location URI, otherwise it is null if it does not exist

Remember the location you specified for the method you created:

If you don't want to rely on static resource paths, you can get the current URI path from the uriinfo class You can do something similar

@Path("/customers")
public class CustomerResource {
    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public Response createCustomer(Customer customer,@Context UriInfo uriInfo) {
        int customerId = // create customer and get the resource id
        UriBuilder builder = uriInfo.getAbsolutePathBuilder();
        builder.path(Integer.toString(customerId));
        return Response.created(builder.build()).build();
    }
}

This will create the location... / customers / 1 (or any CustomerID is) and send it as a response

Note that if you want to send entities and responses, you can attach entity (object) to response In the method chain of reponsebuilder

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>