I need to set charset=UTF-8 on all responses from my jersey endpoints.
I've googled a lot, and in search of a configurable solution, it seems
that using a response filter is the way to go.
In
http://jersey.576304.n2.nabble.com/Jersey-and-Charsets-tp5392069p541144
3.html, Paul Sandoz showed the conceptual idea of how this should work:
> Perhaps the best way you can add the charset is to write a response
filter to modify the
> content-type for certain values rather than modifying all your
annotations.
>
> ContainerResponse response;
>
> MediaType m = response.getMediaType();
> if (/ charset not present on m and m requires a charset) {
> // create a new media type adding a charset of UTF-8.
> m = ...
> response.getHttpHeaders().putSingle("Content-Type", m);
> }
I ended up doing pretty much this:
public class UTF8ResponseFilter implements ContainerResponseFilter
{
private static Map<String, String> charset =
Collections.singletonMap("charset", "UTF-8");
@Override
public ContainerResponse filter(ContainerRequest request,
ContainerResponse response) {
MediaType oldType = response.getMediaType();
MediaType newType = new MediaType(oldType.getType(),
oldType.getSubtype(), charset);
response.getHttpHeaders().putSingle("Content-Type",
newType);
return response;
}
}
My single question, then, is this:
-> Is this best practice for setting charset on all responses?
Eirik