0

I want to internationalize my page but I only find solutions with mapping properties file which is not a good way.

http://example.com/action
http://example.com/es/action

I would like to handle URL before controller to understand which language should I return and return that one.

See the example below;

@RequestMapping(value= "/{lang}/action")
public ModelAndView dashboard(@PathVariable String lang) {
    ModelAndView mav; 

    if(lang.equals("")) mav = new ModelAndView("index");
    else if(lang.equals("es") mav = new ModelAndView("index-es");

    ...
}

I know that this is not a good solution either. That is why I need some ideas to solve it?

David Conrad
  • 15,432
  • 2
  • 42
  • 54
likeachamp
  • 765
  • 4
  • 11
  • 21

1 Answers1

0

I Use an interceptor to determain the language and use the build in spring localeResolver to use that info. I first read the url (or where ever the locale is). I use locales with xx-XX format.

private Locale getLocaleFromUrl(String url) {
    Locale result = null;
    String localePart;
    int slashes = url.indexOf('/', 1);
    if (slashes == -1) {
        // Use full URL
        localePart = url.substring(1);
    } else {
        localePart = url.substring(1, slashes);
    }
    int dashPosition = localePart.indexOf('-');
    if (dashPosition > -1) {
        result = new Locale(localePart.substring(0, dashPosition), localePart.substring(dashPosition + 1));
    }
    return result;

}

After that I strip the locale from the incoming url and do something like this:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
boolean redirected = doRedirect(request, response, url, urlLocale, RequestHelper.getContextPath()); 
if (!redirected) {
  String newUrl = stripUrl(locale, url);
if (newUrl.isEmpty()) {
  newUrl = "/";
}
request.setAttribute("gsforwared", Boolean.TRUE);
request.setAttribute("originalUrl", newUrl);
RequestDispatcher rd = request.getRequestDispatcher(newUrl);
rd.forward(request, response);

}

private boolean doRedirect(HttpServletRequest request, HttpServletResponse response, String url, String urlLocale, String contextPath) {
if (StringUtils.startsWith(url, "/".concat(urlLocale))) {
return false;
}
if (url.startsWith("/static")) {
return false;
}
if (url.startsWith("/error")) {
return false;
}
String redirUrl = "/".concat(urlLocale).concat(url);
if (request.getQueryString() != null) {
redirUrl = redirUrl.concat("?").concat(request.getQueryString());
}
response.setHeader("Location", contextPath + redirUrl);
response.sendError(HttpServletResponse.SC_MOVED_PERMANENTLY);
return true;
}

I also add an attribute to the request which I check before doing this, so that I don't get in a continuous loop.

Your request should be forwarded without the locale

bobK
  • 704
  • 2
  • 7
  • 24