Deciding the locale after the user logins may be a bit late for some applications. For example, you might want to use the same Locale that was used in the previous session, before the user logins. For a Web application, it is usually done by use of cookies. With ZK, you can register a request interceptor and manipulates the cookies when the interceptor is called.
A request interceptor is used to intercept each request processed by ZK Loader and ZK Update Engine. It must implements the org.zkoss.zk.ui.util.RequestInterceptor interface. For example,
public class MyLocaleProvider implements org.zkoss.zk.ui.util.RequestInterceptor { public void request(org.zkoss.zk.ui.Session sess, Object request, Object response) { final Cookie[] cookies = ((HttpServletRequest)request).getCookies(); if (cookies != null) { for (int j = cookies.length; --j >= 0;) { if (cookies[j].getName().equals("my.locale")) { //determine the locale String val = cookies[j].getValue(); Locale locale = org.zkoss.util.Locales.getLocale(val); sess.setAttribute(Attributes.PREFERRED_LOCALE, locale); return; } } } } }
To make it effective, you have to register it in WEB-INF/zk.xml as follows. Once registered, the request method is called each time ZK Loader or ZK Update Engine receives a request. Refer to Appendix B in the Developer's Reference for more information about configuration.
<listener> <listener-class>MyLocaleProvider</listener-class> </listener>
Note: An instance of the interceptor is instantiated when it is registered. It is then shared among all requests in the same application. Thus, you have to make sure it can be accessed concurrently (i.e., thread-safe).
Note: The request method is called at very early stage, before the request parameters are parsed. Thus, it is recommended to access them in this method, unless you configured the locale and character encoding properly for the request.