【问题标题】:Vaadin framework get locale from browserVaadin 框架从浏览器获取语言环境
【发布时间】:2017-11-08 14:25:28
【问题描述】:

我正在设置语言环境以进行翻译。 它在会话期间区域设置保持不变时起作用。 但是,如果我在会话中间更改语言环境并重新加载页面,它会保留在旧语言环境中。

您知道从浏览器获取最新语言设置的方法吗?

我的代码:

@SpringUI
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = MainUI.class)
public class MainUI extends UI
{

    @Override
    protected void init(VaadinRequest request)
    {       
        log.debug("MainUI init! locale: {}", getLocale());//or getSession().getLocale()
        messageByLocaleService.setLocale(getLocale());
        ...

我自己找到了解决方案,但我不能 100% 确定这是正确的解决方案。

【问题讨论】:

    标签: spring session internationalization vaadin locale


    【解决方案1】:

    我发现Page.getCurrent().getWebBrowser() 有时会抛出空异常。我还需要一个请求对象来评估 cookie。

    我可以通过VaadinService.getCurrentRequest() 获取请求对象。 因此,我可以从那里获取语言环境并实现单点故障,从而使我的代码更加可靠。

    所以,我目前的答案是:

    Locale locale = VaadinService.getCurrentRequest().getLocale();
    

    【讨论】:

    • 另外,如果你使用 Vaadin 推送,长轮询模式有一个请求,因此有一个语言环境和 cookie。对此的注释是@Push(value=PushMode.MANUAL, transport=Transport.LONG_POLLING)
    【解决方案2】:

    在 Vaadin 应用程序中,我以这种方式获取 Locale(关于浏览器):

     final WebBrowser webBrowser = Page.getCurrent().getWebBrowser();
     Locale locale = webBrowser.getLocale();
    

    方法返回浏览器的默认定位。

    【讨论】:

      【解决方案3】:

      我发现使用 request.getLocale() 可以满足我的要求,这让我很惊讶,因为一些与我非常相似的问题存在相反的问题,即 request.getLocale 不起作用但 session.getLocale 确实起作用。

      代码:

      Locale locale = request.getLocale();
      log.debug("MainUI init! locale: {}", locale);
      messageByLocaleService.setLocale(locale);
      

      另一个建议相反的问题是: other question

      【讨论】:

        猜你喜欢
        • 2020-05-10
        • 2020-01-24
        • 2018-03-29
        • 1970-01-01
        • 2019-12-31
        • 1970-01-01
        • 2016-09-10
        • 2011-05-27
        • 2022-12-10
        相关资源
        最近更新 更多