简体   繁体   中英

Cookie set in web filter is not available in request bean

I'm trying to create a localized JSF web application which allows user to select a language via dropdown. When language is selected, I simulate a redirect to the same page but with URL parameter:

window.location.replace(urlToMyApp + '?locale=DE');

Next, I read 'locale' parameter in application's web filter and write it in a cookie with the same name:

String localeValue = httpRequest.getParameter("locale");
Cookie cookie = new Cookie("locale", localeValue);
cookie.setMaxAge(-1);
cookie.setDomain(cookieDomain);
cookie.setPath(cookiePath);
httpResponse.addCookie(cookie);

Now when I try to read that cookie in request bean init method, cookie is not available. If I select another language via dropdown (EN for example), previously selected language (DE) is read in init method.

I assume that cookie written in filter is not available before next "request - response" cycle, can someone confirm that?

If that's true I'm asking for an idea to translate my application immediately after selecting another language.

Just one thing that I think I need to mention - language dropdown is not part of my application. It's part of some kind of framework for several applications to be included (like portal).

I assume that cookie written in filter is not available before next "request - response" cycle, can someone confirm that?

That's correct.

You've added the new cookie to the response , not to the request. So any attempt to read it from the same request won't work. The cookie will only be available in the request if the browser has actually sent it. But it can only do that if it has obtained the cookie data from a previous response.

If that's true I'm asking for an idea to translate my application immediately after selecting another language.

If the request scoped bean is managed by CDI @Named , then just inject it in the filter and set the locale over there.

@Inject
private Bean bean;

public void doFilter(...) {
    // ...

    bean.setLocale(locale);

    // ...
}

Else if it's not managed by CDI, but by the since JSF 2.3 deprecated @ManagedBean , then manually instantiate it and put it in request scope so that JSF will just reuse the same bean.

public void doFilter(...) {
    // ...

    Bean bean = new Bean();
    bean.init(); // If necessary.
    bean.setLocale(locale);
    request.setAttribute("bean", bean); // "bean" is managed bean name.

    // ...
}

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM