Adding Spring Boot Rest locale Query Param

dougd

Doug Dallas

Posted on July 25, 2018

Adding Spring Boot Rest locale Query Param

As part of a recent project I’ve been working on we had the requirement to be able to change the locale of the response from our endpoints without the need to actually change the underlying browser locale.

Thanks to some Spring magic, to achieve this I extended the HandlerInterceptorAdapter abstract class to allow me to handle any incoming requests.

@Override
public boolean preHandle(HttpServletRequest request, 
                         HttpServletResponse response, Object handler)
{
    // set request locale here
    return true;
}
Enter fullscreen mode Exit fullscreen mode

From within the preHandle override I took the locale query parameter and set the set the locale on LocaleResolver to that taken from the query param.

The code looks a bit like this:

Locale localeFromRequest = RequestContextUtils.getLocale(request);

String queryParameterLocale = request.getParameter("locale");

if (queryParameterLocale != null) {
   localeFromRequest = StringUtils.parseLocaleString(queryParameterLocale);
}

// set the new locale
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
localeResolver.setLocale(request, response, localeFromRequest);

Enter fullscreen mode Exit fullscreen mode

Finally, in order to activate the newly added Interceptor adapter you need to add it to your WebMvc configuration. See the example below, in my case I’ve named my interceptor RequestLocaleInterceptor.

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter
{
    @Autowired
    private RequestLocaleInterceptor requestLocaleInterceptor;

    /**
     * {@inheritDoc}
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        registry.addInterceptor(requestLocaleInterceptor).addPathPatterns("/**");
    }
}
Enter fullscreen mode Exit fullscreen mode

From then on any REST calls automagically inherit the locale query parameter that sets the locale context.

For example: GET /rest/orderDetails?locale=fr_FR

💖 💪 🙅 🚩
dougd
Doug Dallas

Posted on July 25, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related