01: /*
02: * Copyright 2002-2005 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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:
17: package org.springframework.web.servlet.i18n;
18:
19: import java.util.Locale;
20:
21: import javax.servlet.ServletException;
22: import javax.servlet.http.HttpServletRequest;
23: import javax.servlet.http.HttpServletResponse;
24:
25: import org.springframework.beans.propertyeditors.LocaleEditor;
26: import org.springframework.web.servlet.LocaleResolver;
27: import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
28: import org.springframework.web.servlet.support.RequestContextUtils;
29:
30: /**
31: * Interceptor that allows for changing the current locale on every request,
32: * via a configurable request parameter.
33: *
34: * @author Juergen Hoeller
35: * @since 20.06.2003
36: * @see org.springframework.web.servlet.LocaleResolver
37: */
38: public class LocaleChangeInterceptor extends HandlerInterceptorAdapter {
39:
40: /**
41: * Default name of the locale specification parameter: "locale".
42: */
43: public static final String DEFAULT_PARAM_NAME = "locale";
44:
45: private String paramName = DEFAULT_PARAM_NAME;
46:
47: /**
48: * Set the name of the parameter that contains a locale specification
49: * in a locale change request. Default is "locale".
50: */
51: public void setParamName(String paramName) {
52: this .paramName = paramName;
53: }
54:
55: public boolean preHandle(HttpServletRequest request,
56: HttpServletResponse response, Object handler)
57: throws ServletException {
58:
59: String newLocale = request.getParameter(this .paramName);
60: if (newLocale != null) {
61: LocaleResolver localeResolver = RequestContextUtils
62: .getLocaleResolver(request);
63: if (localeResolver == null) {
64: throw new IllegalStateException(
65: "No LocaleResolver found: not in a DispatcherServlet request?");
66: }
67: LocaleEditor localeEditor = new LocaleEditor();
68: localeEditor.setAsText(newLocale);
69: localeResolver.setLocale(request, response,
70: (Locale) localeEditor.getValue());
71: }
72: // Proceed in any case.
73: return true;
74: }
75:
76: }
|