定义默认语言环境并处理Spring Locale Interceptor的异常 [英] Define default locale and treat exceptions for Spring Locale Interceptor
问题描述
是否可以定义应该加载的默认语言环境,以防用户设置?lang = unknownlang ?
Is it possible to define a default locale that should be loaded in case the user sets ?lang=unknownlang ?
在我的春天-servlet.xml我有:
In my spring-servlet.xml i have:
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="pt" />
</bean>
此外,如果我在我的网址参数中指定了无效字符,例如?lang = p @ t,spring会抛出一个应该处理的异常,我该怎么做?
Also if i specify invalid characters in my url param like ?lang=p@t, spring throws an exception that should be handled, how would i go about that ?
Error 500: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Locale part "'" contains invalid characters
推荐答案
我设法解决了这些问题。
I managed to solve these problems.
关于默认语言环境,只要资源包中有默认的.properties文件,spring就会在内部解决。
Regarding the default locale, spring will solve that internally as long as there is a default .properties file in the resource bundle.
所以在我的情况下,必须有一个xxx_pt.properties xxx_en.properties和一个xxx.properties。
So in my case there would have to be a xxx_pt.properties xxx_en.properties and a xxx.properties.
对于异常处理,我实际上必须覆盖LocaleChangeInterceptor类的preHandle方法并捕获异常:
For the exception handling I actually had to override the preHandle method of the LocaleChangeInterceptor class and catch the exception:
spring-servlet.xml
<bean id="localeChangeInterceptor"
class="com.xxx.xxx.LanguageExceptionHandler">
<property name="paramName" value="lang" />
</bean>
LanguageExceptionHandler.java
public class LanguageExceptionHandler extends LocaleChangeInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
try {
super.preHandle(request, response, handler);
} catch (ServletException e) {
DebugLogger.writeError("ServletException", e);
} catch (IllegalArgumentException e) {
DebugLogger.writeError("IllegalArgumentException", e);
}
return true;
}
}
虽然根据这个,在较新版本的Spring中应该以不同的方式处理无效字符。
Although according to this, invalid characters should be handled differently in newer versions of Spring.
这篇关于定义默认语言环境并处理Spring Locale Interceptor的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!