1. /*
  2. * Copyright 2002-2004 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.web.servlet.support;
  17. import java.util.Locale;
  18. import java.util.ResourceBundle;
  19. import javax.servlet.ServletException;
  20. import javax.servlet.http.HttpServletRequest;
  21. import javax.servlet.jsp.jstl.core.Config;
  22. import javax.servlet.jsp.jstl.fmt.LocalizationContext;
  23. import org.springframework.context.MessageSource;
  24. import org.springframework.context.support.MessageSourceResourceBundle;
  25. /**
  26. * Helper class for preparing JSTL views.
  27. * @author Juergen Hoeller
  28. * @since 20.08.2003
  29. */
  30. public abstract class JstlUtils {
  31. public static final String REQUEST_SCOPE_SUFFIX = ".request";
  32. /**
  33. * Exposes JSTL-specific request attributes specifying locale
  34. * and resource bundle for JSTL's formatting and message tags,
  35. * using Spring's locale and message source.
  36. * @param request current HTTP request
  37. * @param messageSource the MessageSource to expose,
  38. * typically the current application context
  39. * @throws ServletException
  40. */
  41. public static void exposeLocalizationContext(HttpServletRequest request, MessageSource messageSource)
  42. throws ServletException {
  43. // add JSTL locale and LocalizationContext request attributes
  44. Locale jstlLocale = RequestContextUtils.getLocale(request);
  45. ResourceBundle bundle = new MessageSourceResourceBundle(messageSource, jstlLocale);
  46. LocalizationContext jstlContext = new LocalizationContext(bundle, jstlLocale);
  47. // for JSTL implementations that stick to the config names (e.g. Resin's)
  48. request.setAttribute(Config.FMT_LOCALIZATION_CONTEXT, jstlContext);
  49. request.setAttribute(Config.FMT_LOCALE, jstlLocale);
  50. // for JSTL implementations that append the scope to the config names (e.g. Jakarta's)
  51. request.setAttribute(Config.FMT_LOCALIZATION_CONTEXT + REQUEST_SCOPE_SUFFIX, jstlContext);
  52. request.setAttribute(Config.FMT_LOCALE + REQUEST_SCOPE_SUFFIX, jstlLocale);
  53. }
  54. }