Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define default locale and treat exceptions for Spring Locale Interceptor

Is it possible to define a default locale that should be loaded in case the user sets ?lang=unknownlang ?

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>

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&#59; nested exception is java.lang.IllegalArgumentException: Locale part &quot;&#39;&quot; contains invalid characters
like image 911
mfreitas Avatar asked Nov 23 '22 16:11

mfreitas


1 Answers

I managed to solve these problems.

Regarding the default locale, spring will solve that internally as long as there is a default .properties file in the resource bundle.

So in my case there would have to be a xxx_pt.properties xxx_en.properties and a xxx.properties.

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;
    }
}

Although according to this, invalid characters should be handled differently in newer versions of Spring.

like image 186
mfreitas Avatar answered Dec 06 '22 00:12

mfreitas