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