2

Im trying to find a way to honour the locale for the response depending on the Accept-Language header on the request. Im using Jersey implementation. This would be for the Restful side of the application. We already have it covered for the WebApplication side (JSF) but Jersey/JAXRS isnt cooperating.

So basically say I need to return an error response, I would like to send a string back saying "Problem" for an English locale and "Problema" for a Spanish locale.

So far i found this similar post but no concrete answer was given - Implementing a Locale provider that works in JSF and JAX-RS

Your help is appreciated

update:

So far I can get the locale by doing this:

@Controller @Path("/test")
@Produces("plain/text")
public class TestRouteController implements Serializable{

@GET
@RestrictedRoute(permissions={SCConstant.PERMISSION_SEARCH_VIEW_CLIENT})
public Response testMethong(@Context HttpServletRequest request){
    String message = "Locale in request is " + request.getLocale(); 
    return ResponseGenerator.response(message);
}

}

Then I would like to honour the locale of the String message that I;m sending back. If have seen this:

  if(request.getLocale() == "sp-VE")
       message = "El locale en la requesta es " + request.getLocale();
  else if(request.getLocale() == "sp-MX")
       message = "La localizacion en la requesta es " + request.getLocale();

I cant do this because I want to be localize many things.

Community
  • 1
  • 1
allegjdm93
  • 592
  • 6
  • 24

1 Answers1

3

Everything you seem to be missing is a ResourceBundle. My linked question only gets interesting if you allow users to have a differing locale choice from their Accept-Language header (eg, by having them select their locale via a JSF widget and storing the result in their session).

However, if you're fine with what request.getLocale() returns, you can just grab a ResourceBundle for your locale and return that:

@Path("/test")
@Produces(MediaType.TEXT_PLAIN)
public class TestRouteController {

    @GET
    public Response testMethong(@Context HttpServletRequest request) {
        Locale requestLocale = request.getLocale();
        ResourceBundle l8n = ResourceBundle.getBundle("msgs", requestLocale);

        return Response.ok(l8n.getString("problem")).build();
    }
}

Where the getBundle("msgs", ...) would try to fetch a ResourceBundle using the current classloader as the documentation explains. This means you can have one property file per supported locale (if you're using JSF chances are you already have them...) anywhere your classloader can find them and the resource bundle magic will do the work for you.

The files will look like so

msgs_sp_VE.properties:

problem = El locale en la requesta es

msgs_sp_MX.properties:

problem = La localizacion en la requesta es
mabi
  • 5,279
  • 2
  • 43
  • 78