小编典典

Spring Boot-单击更改语言环境

spring-boot

我正在为我的Web应用程序使用SpringBoot,并且我想将2个按钮绑定到2种不同的语言,但是我不知道如何正确地进行操作。

我试图这样做,但是没有用。

@RequestMapping("/language")
public class LanguageController {

    @RequestMapping("esp")
    public String setEsp(SessionLocaleResolver session)
    {
        Locale esp = new Locale("es_ES" );
        session.setDefaultLocale(esp);
        return "index";
    }

    @RequestMapping("eng")
    public String setEng(SessionLocaleResolver session)
    {
        session.setDefaultLocale(Locale.ENGLISH);
        return "index";
    }
}

阅读 585

收藏
2020-05-30

共1个答案

小编典典

当前设置中存在 几个错误

  1. SessionLocaleResolver 支持的处理方法参数-因此你目前的代码会导致一个NullpointerException调用任何的处理方法时。为了获得访问权限,SessionLocaleResolver您必须在Spring Boot中进行设置Application.java
  2. 一旦SessionLocaleResolver可以自动连线到Controller中,您应该打电话setLocale而不是它setDefaultLocale,一切应该开始工作。
  3. 由于更改Locale是一个常见的用例,因此Spring提供了LocaleChangeInterceptor,它 消除了对自定义逻辑的需求 ,并使您的处理程序方法保持整洁。

例如有关如何在Spring
Boot中进行设置的示例代码,请检查this

2020-05-30