1
1
/*
2
- * Copyright 2002-2013 the original author or authors.
2
+ * Copyright 2002-2015 the original author or authors.
3
3
*
4
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
5
* you may not use this file except in compliance with the License.
20
20
import javax .servlet .http .HttpServletRequest ;
21
21
import javax .servlet .http .HttpServletResponse ;
22
22
23
+ import org .springframework .util .ObjectUtils ;
23
24
import org .springframework .util .StringUtils ;
24
25
import org .springframework .web .servlet .LocaleResolver ;
25
26
import org .springframework .web .servlet .handler .HandlerInterceptorAdapter ;
@@ -42,6 +43,8 @@ public class LocaleChangeInterceptor extends HandlerInterceptorAdapter {
42
43
43
44
private String paramName = DEFAULT_PARAM_NAME ;
44
45
46
+ private String [] httpMethods ;
47
+
45
48
46
49
/**
47
50
* Set the name of the parameter that contains a locale specification
@@ -59,21 +62,53 @@ public String getParamName() {
59
62
return this .paramName ;
60
63
}
61
64
65
+ /**
66
+ * Configure the HTTP method(s) over which the locale can be changed.
67
+ * @param httpMethods the methods
68
+ * @since 4.2
69
+ */
70
+ public void setHttpMethods (String ... httpMethods ) {
71
+ this .httpMethods = httpMethods ;
72
+ }
73
+
74
+ /**
75
+ * Return the configured HTTP methods.
76
+ * @since 4.2
77
+ */
78
+ public String [] getHttpMethods () {
79
+ return this .httpMethods ;
80
+ }
81
+
62
82
63
83
@ Override
64
84
public boolean preHandle (HttpServletRequest request , HttpServletResponse response , Object handler )
65
85
throws ServletException {
66
86
67
87
String newLocale = request .getParameter (this .paramName );
68
88
if (newLocale != null ) {
69
- LocaleResolver localeResolver = RequestContextUtils .getLocaleResolver (request );
70
- if (localeResolver == null ) {
71
- throw new IllegalStateException ("No LocaleResolver found: not in a DispatcherServlet request?" );
89
+ if (checkHttpMethod (request .getMethod ())) {
90
+ LocaleResolver localeResolver = RequestContextUtils .getLocaleResolver (request );
91
+ if (localeResolver == null ) {
92
+ throw new IllegalStateException (
93
+ "No LocaleResolver found: not in a DispatcherServlet request?" );
94
+ }
95
+ localeResolver .setLocale (request , response , StringUtils .parseLocaleString (newLocale ));
72
96
}
73
- localeResolver .setLocale (request , response , StringUtils .parseLocaleString (newLocale ));
74
97
}
75
98
// Proceed in any case.
76
99
return true ;
77
100
}
78
101
102
+ private boolean checkHttpMethod (String currentMethod ) {
103
+ if (ObjectUtils .isEmpty (getHttpMethods ())) {
104
+ return true ;
105
+ }
106
+ for (String httpMethod : getHttpMethods ()) {
107
+ if (httpMethod .equalsIgnoreCase (currentMethod )) {
108
+ return true ;
109
+ }
110
+ }
111
+ return false ;
112
+ }
113
+
79
114
}
0 commit comments