2011-07-15 77 views
2

地圖網址有沒有什麼解決基於URL和在另一方面地圖的請求區域沒有任何附加要求的好方法?用語言標識符

例如

http://example.com/ru/news  
http://example.com/iw/news 

,並在控制器中仍然使用標準映射

@Controller 
@RequestMapping(value = "/news") 
public class NewsController { 

    // Controller methods ...  

} 

回答

1

我不知道出的現成的解決方案,這一點,但它很容易使用自定義攔截器來實現和一些明智地選擇映射。

寫的HandlerInterceptor的實施,使該區域的字符串從請求URI中提取它實現preHandle,然後標記與該區域的請求(see the source code for類似LocalChangeInterceptor,它做了類似的事情,你需要什麼,但使用一個請求參數,而不是一個路徑變量)。

然後wire it up使用<mvc:interceptor>例如

<mvc:interceptors> 
    <mvc:interceptor> 
     <mapping path="/*"/> 
     <bean class="x.y.MyInterceptor" /> 
    </mvc:interceptor> 
</mvc:interceptors> 

然後,您可以放鬆請求映射控制器上容忍(和忽略)的URI的語言環境部分:

@Controller 
@RequestMapping(value = "*/news") 
public class NewsController { 

    // Controller methods ...  

} 
2

你可以寫一個自定義的攔截器,就像LocaleChangeInterceptor

這是一個使用一個樣本實現正則表達式模式(大部分代碼從LocaleChangeInterceptor複製):

public class CustomLocaleChangeInterceptor extends HandlerInterceptorAdapter { 

    private Pattern localePattern; 

    public void setLocalePattern(final String localePattern) { 
     Assert.isTrue(localePattern.matches(".*\\(.*\\).*"), "Your pattern needs to define a match group"); 
     this.localePattern = Pattern.compile(localePattern); 
    } 

    @Override 
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) 
      throws ServletException { 

     final String pathTranslated = request.getPathTranslated(); 
     if (pathTranslated != null) { 

      final Matcher matcher = localePattern.matcher(pathTranslated); 
      if (matcher.find()) { 
       final String newLocale = matcher.group(1); 
       if (newLocale != null) { 
        final LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); 
        if (localeResolver == null) { 
         throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?"); 
        } 
        final LocaleEditor localeEditor = new LocaleEditor(); 
        localeEditor.setAsText(newLocale); 
        localeResolver.setLocale(request, response, (Locale) localeEditor.getValue()); 
       } 
      } 
     } 
     // Proceed in any case. 
     return true; 

    } 

} 

線這樣的:

<bean id="localeChangeInterceptor" 
     class="foo.bar.CustomLocaleChangeInterceptor"> 
    <property name="localePattern" value="\b([a-z]{2})\b"/> 
</bean 
+0

我認爲你需要使用request.servletpath()代替request.getPathTranslated(); – madz