从控制器更改春季内部化语言

时间:2019-03-05 13:07:55

标签: spring spring-boot spring-mvc internationalization spring-internationalization

在弹簧内部化中,我正在使用此配置

@Bean
public LocaleResolver localeResolver() {
    //for this demo, we'll use a SessionLocaleResolver object
    //as the name implies, it stores locale info in the session
    SessionLocaleResolver resolver = new SessionLocaleResolver();

    //default to US locale
    resolver.setDefaultLocale(Locale.US);

    //get out
    return resolver;
}


/**
 * This interceptor allows visitors to change the locale on a per-request basis
 * @return a LocaleChangeInterceptor object
 */
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    //instantiate the object with an empty constructor
    LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();

    //the request param that we'll use to determine the locale
    interceptor.setParamName("lang");

    //get out
    return interceptor;
}


/**
 * This is where we'll add the intercepter object
 * that handles internationalization
 */
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}

而且我可以从html更改语言,即脚本及其正常工作

  

window.location.replace('?lang ='+ selectedOption);

但是有什么方法可以从控制器进行更改,因为首选语言将存储在DB内

因此将提取语言并进行设置

示例

u = ucr.findByNameContaining(name);
u.getLanguage 
<< i have to set language returned from above line >>

@RequestMapping(value = {"/welcome"}, method = RequestMethod.POST)
public String notificationChannelSearchPost(ModelMap model,HttpSession session
        ,@RequestParam(value="name", defaultValue="") String name) {


     u = ucr.findByNameContaining(name);
     u.getLanguage 
<< i have to set language returned from above line >>
    return "welcom.html";
}

谢谢

1 个答案:

答案 0 :(得分:0)

您可以通过执行以下操作在Java中手动设置spring区域设置

LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);             
localeResolver.setLocale(request, response,new Locale(u.getLanguage()));