Java 如何处理多语言URL Spring mvc

Java 如何处理多语言URL Spring mvc,java,spring,url,internationalization,translation,Java,Spring,Url,Internationalization,Translation,我想国际化我的网页,但我只找到解决方案与映射属性文件,这不是一个好办法 http://example.com/action http://example.com/es/action 我知道这也不是一个好的解决办法。这就是为什么我需要一些想法来解决它?我使用一个拦截器来阻止该语言,并使用内置的spring localeResolver来使用该信息。我首先读取url或区域设置所在的位置。我使用xx-xx格式的区域设置 private Locale getLocaleFromUrl(String ur

我想国际化我的网页,但我只找到解决方案与映射属性文件,这不是一个好办法

http://example.com/action http://example.com/es/action
我知道这也不是一个好的解决办法。这就是为什么我需要一些想法来解决它?

我使用一个拦截器来阻止该语言,并使用内置的spring localeResolver来使用该信息。我首先读取url或区域设置所在的位置。我使用xx-xx格式的区域设置

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;

}
之后,我从传入url中删除区域设置,并执行如下操作:

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);
}

我还向请求添加了一个属性,在执行此操作之前检查该属性,这样我就不会进入连续循环

您的请求应在不使用区域设置的情况下转发

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;
}