How do I support localization with Jersey?

java, jersey, localization, rest, url-rewriting

Solution

You can make the `/en/` or the `/fr/` part a variable. Then set your locale to the value of the variable. Here's an example:

@Path("/{locale}/username")
public class UserResource {

   @GET
   @Produces("text/xml")
   public String getUser(@PathParam("locale") String locale) {
       ...
   }
}

But that may not be the best way to go about it. After answering, I found this other SO question that is a better way to solve the problem: Getting the client locale in a jersey request With this way, you don't need to add this to the URL. Just make the client set a header.

Problem

I am designing a REST API that I would like to be localizable in the future. Therefore I am defining the URLs to be of the form ``` /en/<resource_url> ``` With the intention of being able to support ``` /fr/<resource_url> ``` In the future if need be. However I only want to define each resource url service once. Therefore I figure I need to get the URL parsed and rewritten without the language piece of the URL before it is matched to services. Finally that language should be made available to the services somehow for them to localize if necessary. How can I achieve this? I am using Jersey 1.17 inside Jetty container embedded in a larger server process.

Original source

Related problems