Adder
Adder

Reputation: 5868

Vaadin framework get locale from browser

I am setting the locale for the purpose of translation. It works when the locale stays the same during a session. However, if I change the locale in the middle of a session and reload the page, it stays in the old locale.

Do you know of a way to get the up-to-date language settings from the browser?

My Code:

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

I found a solution myself, but I am not 100% sure this is the correct solution.

Upvotes: 1

Views: 2573

Answers (3)

Adder
Adder

Reputation: 5868

I found that Page.getCurrent().getWebBrowser() sometimes throws a null exception. I also need a request object for the purpose of evaluating cookies.

I can get a request object by VaadinService.getCurrentRequest(). So I can get the locale from there and have a single-point-of-failure, making my code more reliable.

So, my current answer is:

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

Upvotes: 4

newOne
newOne

Reputation: 698

In Vaadin application I get Locale in this way (regarding browser) :

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

Methods return the default locate of the browser.

Upvotes: 2

Adder
Adder

Reputation: 5868

I found that using request.getLocale() does what I want, which kind of surprises me, because some question very similar to mine had the oposite problem that request.getLocale didn't work but session.getLocale did work.

Code:

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

The other question which advises the opposite is this: other question

Upvotes: 0

Related Questions