/ Web Development

How to Implement Localization in a Spring Boot Application with Dynamic Language Switching

Blog Image
Creator Image
Bashar Alshaibani
25 Jul 2024 -
9 min Reading time

كيفية تنفيذ الترجمة في تطبيق سبرنج بوت مع التبديل الديناميكي للغات


Localization is essential for creating applications that cater to diverse user bases by supporting multiple languages and regions. In this guide, we’ll walk you through setting up localization in a Spring Boot application, focusing on switching between English and Arabic languages dynamically using jQuery.

Step 1: Configuring Spring Boot for Localization

  1. Define Message Source Configuration

    To handle localized messages, you need to configure the MessageSource bean. This bean will manage the message bundles used for different languages.

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.support.ReloadableResourceBundleMessageSource;
    import org.springframework.web.servlet.i18n.CookieLocaleResolver;
    import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    import java.util.Locale;
    
    @Configuration
    public class MessageConfig {
    
        @Bean
        public ReloadableResourceBundleMessageSource messageSource() {
            ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
            messageSource.setBasename("classpath:messages");
            messageSource.setDefaultEncoding("UTF-8");
            return messageSource;
        }
    
        @Bean
        public CookieLocaleResolver localeResolver() {
            CookieLocaleResolver localeResolver = new CookieLocaleResolver();
            localeResolver.setDefaultLocale(Locale.ENGLISH); // Default locale
            localeResolver.setCookieName("language"); // Cookie name to store locale
            localeResolver.setCookieMaxAge(7 * 24 * 60 * 60); // Cookie expiration (e.g., 7 days)
            return localeResolver;
        }
    
        @Bean
        public LocaleChangeInterceptor localeChangeInterceptor() {
            LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
            localeChangeInterceptor.setParamName("lang"); // Reads 'lang' parameter from URL
            return localeChangeInterceptor;
        }
    }
    
  2. Configure Resource Handlers

    Ensure that static resources are served correctly.

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/**")
                    .addResourceLocations("classpath:/static/", "classpath:/images/")
                    .setCachePeriod(3600); // Cache resources for 1 hour
        }
    
        @Autowired
        private LocaleChangeInterceptor localeChangeInterceptor;
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(localeChangeInterceptor);
        }
    }
    
  3. Create Message Files

    Create properties files for English and Arabic translations in src/main/resources:

    messages.properties (default)

    greeting=Hello
    farewell=Goodbye
    

    messages_ar.properties (Arabic)

    greeting=مرحبا
    farewell=وداعا
    

Step 2: Dynamic Language Switching with jQuery

To enable users to switch languages dynamically, use jQuery to handle the language change and update the UI accordingly.

  1. Include jQuery and js-cookie

    Make sure to include jQuery and the js-cookie library in your HTML file.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
    
  2. Add HTML for Language Icons

    Add flags or icons to your HTML to represent the languages.

    <div class="flex justify-end w-auto px-2">
        <div class="w-6 h-6 cursor-pointer" data-lang="en" id="language-icon">
            <img src="/images/united-kingdom.png" alt="English">
        </div>
        <div class="w-6 h-6 cursor-pointer" data-lang="ar" id="language-icon-ar">
            <img src="/images/arabic.png" alt="Arabic">
        </div>
    </div>
    
  3. Write JavaScript for Language Switching

    Implement JavaScript to handle language changes.

    <script>
        function switchLanguage(lang) {
            console.log("Switching language to:", lang);
            Cookies.set('language', lang, { expires: 7 });
            location.reload();
        }
    
        $('#language-icon').on('click', function() {
            switchLanguage('en');
            $('#language-icon').hide();
            $('#language-icon-ar').show();
        });
    
        $('#language-icon-ar').on('click', function() {
            switchLanguage('ar');
            $('#language-icon-ar').hide();
            $('#language-icon').show();
        });
    
        // Check the current language and set the appropriate icon
        const currentLang = Cookies.get('language') || 'en';
        console.log("Current language:", currentLang);
        if (currentLang === 'ar') {
            $('#language-icon-ar').hide();
            $('#language-icon').show();
        } else {
            $('#language-icon').hide();
            $('#language-icon-ar').show();
        }
    </script>
    

Conclusion

By following these steps, you can effectively localize your Spring Boot application to support both English and Arabic. The combination of backend configuration and frontend JavaScript allows users to switch languages seamlessly, enhancing their experience and accessibility.

Feel free to expand this setup to include more languages and messages as needed for your application!