LibraryLink ToToggle FramesPrintFeedback

Handling more advanced responses

The Response class methods provide short cuts for creating responses for common cases. When you need to address more complicated cases such as specifying cache control directives, adding custom HTTP headers, or sending a status not handled by the Response class, you need to use the ResponseBuilder classes methods to populate the response before using the build() method to generate the response object.

[Tip]Tip

As discussed in Getting a response builder, you can use the Apache CXF ResponseBuilderImpl class to create a response builder instance that can be manipulated directly.

Custom headers are added to a response using the ResponseBuilder class' header() method. The header() method takes two parameters:

  • name—a string specifying the name of the header

  • value—a Java object containing the data stored in the header

You can set multiple headers on the message by calling the header() method repeatedly.

Example 4.7 shows code for adding a header to a response.


Custom headers are added to a response using the ResponseBuilder class' cookie() method. The cookie() method takes one or more cookies. Each cookie is stored in a javax.ws.rs.core.NewCookie object. The easiest of the NewCookie class' contructors to use takes two parameters:

  • name—a string specifying the name of the cookie

  • value—a string specifying the value of the cookie

You can set multiple cookies by calling the cookie() method repeatedly.

Example 4.8 shows code for adding a cookie to a response.


[Warning]Warning

Calling the cookie() method with a null parameter list erases any cookies already associated with the response.

When you want to return a status other than one of the statuses supported by the Response class' helper methods, you can use the ResponseBuilder class' status() method to set the response's status code. The status() method has two variants. One takes an int that specifies the response code. The other takes a Response.Status object to specify the response code.

The Response.Status class is an enumeration enclosed in the Response class. It has entries for most of the defined HTTP response codes.

Example 4.9 shows code for setting the response status to 404 Not Found.


The ResponseBuilder class' cacheControl() method allows you to set the cache control headers on the response. The cacheControl() method takes a javax.ws.rs.CacheControl object that specifies the cache control directives for the response.

The CacheControl class has methods that correspond to all of the cache control directives supported by the HTTP specification. Where the directive is a simple on or off value the setter method takes a boolean value. Where the directive requires a numeric value, such as the max-age directive, the setter takes an int value.

Example 4.10 shows code for setting the no-store cache control directive.