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.ServletException;
  19. import javax.servlet.http.HttpServletRequest;
  20. import javax.servlet.http.HttpServletResponse;
  21. import org.springframework.beans.propertyeditors.LocaleEditor;
  22. import org.springframework.web.servlet.LocaleResolver;
  23. import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
  24. import org.springframework.web.servlet.support.RequestContextUtils;
  25. /**
  26. * Interceptor that allows for changing the current locale on every request,
  27. * via a configurable request parameter.
  28. * @author Juergen Hoeller
  29. * @since 20.06.2003
  30. * @see org.springframework.web.servlet.LocaleResolver
  31. */
  32. public class LocaleChangeInterceptor extends HandlerInterceptorAdapter {
  33. public static final String DEFAULT_PARAM_NAME = "locale";
  34. private String paramName = DEFAULT_PARAM_NAME;
  35. /**
  36. * Set the name of the parameter that contains a locale specification
  37. * in a locale change request. Default is "locale".
  38. */
  39. public void setParamName(String paramName) {
  40. this.paramName = paramName;
  41. }
  42. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
  43. throws ServletException {
  44. LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
  45. String newLocale = request.getParameter(this.paramName);
  46. if (newLocale != null) {
  47. LocaleEditor localeEditor = new LocaleEditor();
  48. localeEditor.setAsText(newLocale);
  49. localeResolver.setLocale(request, response, (Locale) localeEditor.getValue());
  50. }
  51. // proceed in any case
  52. return true;
  53. }
  54. }