【问题标题】:spring internalization language change from controller从控制器更改弹簧内部化语言
【发布时间】:2019-03-05 13:07:54
【问题描述】:

在 spring 内部化中我正在使用这个配置

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

但是有什么方法可以从控制器更改它,因为首选语言将存储在数据库中

所以语言将被获取并设置

例子

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    您可以通过执行以下操作在 Java 中手动设置 spring 语言环境

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

    【讨论】:

    • 非常感谢,我确实尝试了上面的行而不是发送新的语言环境,因为我刚刚发送了 u.getlanguage()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 2011-08-06
    • 2014-12-14
    • 1970-01-01
    相关资源
    最近更新 更多