Can you provide an example of changing languages dynamically on the frontend?

Dynamic language switching lets a user change the displayed locale without reloading the whole application or losing their place, typically by combining a client-side language selector with Spring's internationalization (i18n) support. The chosen locale is remembered via a cookie, session, or URL parameter and applied to message resolution on subsequent requests.

Key Points: • A dropdown or menu on the page lets the user pick a language, which is sent to the server as a request parameter, e.g. ?lang=fr. • A LocaleChangeInterceptor registered in Spring MVC detects that parameter and updates the current LocaleResolver. • A CookieLocaleResolver or SessionLocaleResolver persists the chosen locale across subsequent requests so it doesn't reset on every page. • Message bundles (messages_en.properties, messages_fr.properties, etc.) supply translated text, resolved through Spring's MessageSource based on the active locale. • For fully dynamic, no-reload behavior, the front end can instead fetch translated strings via JavaScript/AJAX and swap them into the DOM without a page reload, while still using the server-stored preference for future full page loads.

Example: A user selects "Français" from a dropdown, the browser sends a request with ?lang=fr, LocaleChangeInterceptor updates the session locale, and every subsequent page renders text pulled from messages_fr.properties instead of the default bundle.

Code Example:

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver resolver = new SessionLocaleResolver();
    resolver.setDefaultLocale(Locale.ENGLISH);
    return resolver;
}

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
    interceptor.setParamName("lang");
    return interceptor;
}

Interview Tip: A concise interview answer is:

"I'd add a language dropdown that sends a lang request parameter, register a LocaleChangeInterceptor to catch it, and use a SessionLocaleResolver or CookieLocaleResolver to remember the choice across requests. Spring's MessageSource then resolves text from the matching properties bundle for the active locale on every subsequent page."