users@jersey.java.net

Re: [Jersey] how to set the response encoding ?

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Mon, 31 Aug 2009 11:35:36 +0200

On Aug 29, 2009, at 10:08 PM, Craig McClanahan wrote:

> Felipe Gaúcho wrote:
>>
>> humm.. but I have already a response type..
>>
>> my method:
>>
>> @GET
>> @Produces( { MediaType.APPLICATION_XML,
>> MediaType.APPLICATION_JSON })
>> @Path("{offset}/{limit}/{groupId}")
>> public Collection<PujUserEntity> selectAllByGroup(
>> @PathParam("offset") int offset, @PathParam("limit") int limit,
>> @PathParam("offset") String groupId) {
>> return facade.readAllByGroupId(offset, limit, groupId);
>> }
>>
>>
>> How to set the chraset (and other headers) of the HTTP response ?
>>
> Your resource method is returning the entity
> (Collection<PujUserEntity>) directly. Have it return a "Response"
> object instead.


For instances of Collection< PujUserEntity> make sure you wrap the
instance around an extending instance of GenericEntity<Collection<
PujUserEntity>> otherwise the type information of the collection will
be erased and Jersey will not have enough information on how to
serialize the collection.

Paul.

> Jersey will set the content type and content length for you, but you
> can set any other headers you want as in my example below.
>> On Sat, Aug 29, 2009 at 7:25 PM, Craig
>> McClanahan<Craig.McClanahan_at_sun.com> wrote:
>>
>>> Felipe Gaúcho wrote:
>>>
>>>> How to set the response encoding of my Jersey resources ?
>>>>
>>>> * or other response HTTP headers ?
>>>>
>>>>
>>>>
>>> Have your resource method return a "javax.ws.rs.core.Resonse"
>>> instead of an
>>> entity object class directly. You can use its "builder pattern"
>>> APIs to add
>>> as many headers as you like:
>>>
>>> @GET
>>> public Response get(...) {
>>>
> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Note the return type from the method
>>> Object entity = ...; // The object you would normally have
>>> been
>>>
> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This would be
> "facade.readAllByGroupId(offset, limit, groupId)" for you (or you
> could just pass this directly as the argument to the ok() method).
>
>>> returning
>>> return Response.ok(entity).
>>> header("Content-Language", "en-us").
>>>
> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Set any header you want like this.
> There are also shortcuts like language() to set the Content-Language
> header, tag() to set an ETag, and so on.
>
>
>>> build();
>>> }
>>>
>>> There are also shortcut methds for many of the common HTTP
>>> headers, as well
>>> as a way to set status codes other than 200.
>>>
>>> Craig
>>>
>>>
> Craig
>
>>> ---------------------------------------------------------------------
>>> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
>>> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>>>
>>>
>>>
>>
>>
>>
>>
>