SessionLocaleResolver.java
Upload User: jiancairen
Upload Date: 2007-08-27
Package Size: 26458k
Code Size: 2k
Category:

Java Develop

Development Platform:

Java

  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
  28.  * <code>setLocale</code>, e.g. responding to a locale change request.
  29.  *
  30.  * @author Juergen Hoeller
  31.  * @since 27.02.2003
  32.  * @see #setLocale
  33.  */
  34. public class SessionLocaleResolver implements LocaleResolver {
  35. /**
  36.  * Name of the session attribute that holds the locale.
  37.  * Only used internally by this implementation.
  38.  * Use <code>RequestContext(Utils).getLocale()</code>
  39.  * to retrieve the current locale in controllers or views.
  40.  * @see org.springframework.web.servlet.support.RequestContext#getLocale
  41.  * @see org.springframework.web.servlet.support.RequestContextUtils#getLocale
  42.  */
  43. public static final String LOCALE_SESSION_ATTRIBUTE_NAME = SessionLocaleResolver.class.getName() + ".LOCALE";
  44. public Locale resolveLocale(HttpServletRequest request) {
  45. Locale locale = (Locale) WebUtils.getSessionAttribute(request, LOCALE_SESSION_ATTRIBUTE_NAME);
  46. // specific locale, or fallback to accept header locale?
  47. return (locale != null ? locale : request.getLocale());
  48. }
  49. public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
  50. WebUtils.setSessionAttribute(request, LOCALE_SESSION_ATTRIBUTE_NAME, locale);
  51. }
  52. }