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.i18n;
  17. import java.util.Locale;
  18. import javax.servlet.http.HttpServletRequest;
  19. import javax.servlet.http.HttpServletResponse;
  20. import org.springframework.web.servlet.LocaleResolver;
  21. import org.springframework.web.util.WebUtils;
  22. /**
  23. * Implementation of LocaleResolver that uses a locale attribute in the user's
  24. * session in case of a custom setting, with a fallback to the accept header locale.
  25. * This is most appropriate if the application needs user sessions anyway.
  26. *
  27. * <p>Custom controllers can override the user's locale by calling setLocale,
  28. * e.g. responding to a locale change request.
  29. *
  30. * @author Juergen Hoeller
  31. * @since 27.02.2003
  32. */
  33. public class SessionLocaleResolver implements LocaleResolver {
  34. /**
  35. * Name of the session attribute that holds the locale. Only used
  36. * internally by this implementation. Use RequestContext.getLocale()
  37. * to retrieve the current locale in controllers or views.
  38. * @see org.springframework.web.servlet.support.RequestContext#getLocale
  39. */
  40. public static final String LOCALE_SESSION_ATTRIBUTE_NAME = SessionLocaleResolver.class.getName() + ".LOCALE";
  41. public Locale resolveLocale(HttpServletRequest request) {
  42. Locale locale = (Locale) WebUtils.getSessionAttribute(request, LOCALE_SESSION_ATTRIBUTE_NAME);
  43. // specific locale, or fallback to request locale?
  44. return (locale != null ? locale : request.getLocale());
  45. }
  46. public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
  47. WebUtils.setSessionAttribute(request, LOCALE_SESSION_ATTRIBUTE_NAME, locale);
  48. }
  49. }