Returning additional metadata with responses

We discussed a few examples in the previous section for retrieving resources via the HTTP GET request. The resource class implementations that we used in these examples were simply returning plain Java constructs in response to the method call. What if you want to return extra metadata, such as the Cache-Control header or the status code, along with the result (resource representation)?

JAX-RS allows you to return additional metadata via the javax.ws.rs.core.Response class, which wraps the entity and any additional metadata, such as the HTTP headers, HTTP cookie, and status code. You can create a Response instance by using javax.ws.rs.core.Response.ResponseBuilder as a factory. The following example demonstrates the use of the Response class to return the response content along with the additional HTTP header fields:

//Other imports removed for brevity 
import javax.ws.rs.core.CacheControl; 
import javax.ws.rs.core.Response; 
import javax.ws.rs.core.Response.ResponseBuilder;  
 
@GET 
@Produces(MediaType.APPLICATION_JSON) 
public Response findAllDepartmentsByName(@QueryParam("name") 
String deptName) { List<Department> depts= findAllMatchingDepartmentEntities (deptName); //Sets cache control directive to the response CacheControl cacheControl = new CacheControl(); //Cache the result for a day cacheControl.setMaxAge(86400); return Response.ok(). cacheControl(cacheControl).entity(depts).build(); }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.191.134