DEV Community

Doug Dallas
Doug Dallas

Posted on

2 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay