tech.mhuang.pacebox.springboot.autoconfiguration.validate.LocaleInterceptor Maven / Gradle / Ivy
The newest version!
package tech.mhuang.pacebox.springboot.autoconfiguration.validate;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;
import tech.mhuang.pacebox.springboot.core.constans.Global;
/**
* 国际化切换拦截器
*
* @author mhuang
* @since 1.0.0
*/
public class LocaleInterceptor extends LocaleChangeInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//getParameter 改为 getHeader
String newLocale = request.getHeader(Global.LANGUAGE);
if (newLocale != null) {
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
if (localeResolver == null) {
throw new IllegalStateException(
"No LocaleResolver found: not in a DispatcherServlet request?");
}
try {
localeResolver.setLocale(request, response, parseLocaleValue(newLocale));
} catch (IllegalArgumentException ex) {
if (isIgnoreInvalidLocale()) {
if (logger.isDebugEnabled()) {
logger.debug("Ignoring invalid locale value [" + newLocale + "]: " + ex.getMessage());
}
} else {
throw ex;
}
}
}
// Proceed in any case.
return true;
}
}