Dino Lupo     About     Archive     Feed

JSTL locale resolver for Spring

This locale resolver reads the locale from JSTL configuration. If you need to use the same locale both for Spring and JSTL you have to do the following:

  1. Cut-Paste the I18nJstlLocaleResolver class code into your project.
  2. Add the Spring bean “localeResolver” definition to your spring configuration file referencing that class.

Here is the code for the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
     
package dl.spring.utils;

import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.jstl.core.Config;

import org.springframework.web.servlet.LocaleResolver;

public class I18nJstlLocaleResolver implements LocaleResolver {

  public Locale resolveLocale(HttpServletRequest request) {
    Locale locale = (Locale) Config.get(request.getSession(), Config.FMT_LOCALE);
        if (locale == null)
        {
            locale = request.getLocale();
        }
        return locale;
  }

  public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    if (locale != null)
      Config.set(request.getSession(),Config.FMT_LOCALE, locale);
  }

}

And here is the code for the localeResolver bean definition (insert it into your spring definition xml file):

1
2
 
<bean id="localeResolver" class="dl.spring.utils.I18nJstlLocaleResolver"/>

See ya!

comments powered by Disqus