RequestAttributeLocaleResolver.java
/**
* Copyright 2014 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys.spring;
import java.util.Locale;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import org.genesys.server.servlet.filter.LocaleURLFilter;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import lombok.extern.slf4j.Slf4j;
/**
* Implementation of LocaleResolver that uses a locale attribute in the user's
* session in case of a custom setting, with a fallback to the specified default
* locale or the request's accept-header locale.
*
* <p>
* This is most appropriate if the application needs user sessions anyway, that
* is, when the HttpSession does not have to be created for the locale.
*
* <p>
* Custom controllers can override the user's locale by calling
* {@code setLocale}, e.g. responding to a locale change request.
*
* @author Juergen Hoeller
* @author Matija Obreza
*
* @see #setDefaultLocale
* @see #setLocale
*/
@Slf4j
public class RequestAttributeLocaleResolver extends AcceptHeaderLocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
Locale requestAttributeLocale = (Locale) request.getAttribute(LocaleURLFilter.REQUEST_LOCALE_ATTR);
if (Objects.equals(getDefaultLocale(), requestAttributeLocale) || requestAttributeLocale == null) {
var headerLocale = super.resolveLocale(request);
log.debug("Using Accept-Language locale: {}", headerLocale);
return headerLocale;
} else {
log.debug("Using path locale: {}", requestAttributeLocale);
return requestAttributeLocale;
}
}
}