Internationalization and localization in Spring MVC

Internationalization and localization in Spring MVC

Internationalization (i18n for short) and localization (l10n for short) are important concepts in building multi-language applications. Spring MVC provides rich support that enables developers to easily handle internationalization and localization needs. This article will introduce how to handle internationalization and localization in Spring MVC and provide sample code.

Insert image description here

What are internationalization and localization?

  • Internationalization (i18n): Internationalization refers to designing and developing applications so that they can easily adapt to different languages ​​and regions. This includes localizing text, date, time, currency, etc. to suit different cultural practices.

  • Localization (Localization - l10n): Localization refers to adapting the interface and content of an application to a specific language and region. This includes translating text, adjusting date and time formats, using local currency symbols, and more to provide a user experience that better matches user expectations.

Internationalization in Spring MVC

Spring MVC supports internationalization in the following ways:

  1. Resource files: Spring MVC allows you to create resource files containing different language versions. These resource files include message source, date and time format, currency format, etc. Different languages ​​and regions will have different resource files.

  2. Locale parsing: Spring MVC LocaleResolverparses the language and region information requested by the client through the interface. By default, it uses Accept-Languagea header to determine the client's preferred language, but you can customize it LocaleResolverto suit your specific needs.

  3. Source: Spring MVC provides MessageSourceinterfaces to load and manage resource files. You can call this in your code MessageSourceto get the localized text.

  4. Tag libraries: Spring MVC provides JSTL tag libraries and view technologies such as Thymeleaf, allowing you to easily localize text in your views.

Create Spring MVC project

First, make sure you have installed the Java development environment and Maven. Next, you can create a new Spring MVC project using Spring Initializer. Select your project configuration at https://start.spring.io/ , then build the project and download it.

Add Spring Web and Thymeleaf dependencies

In the generated project, you need to add dependencies for Spring Web and Thymeleaf. In pom.xmlthe file, make sure the following dependencies have been added:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

This will include all dependencies required by Spring MVC and Thymeleaf.

Configure resource files

In src/main/resourcesthe directory, create a messages.propertiesresource file named to store the default internationalized messages:

greeting.message=Hello, World!

In src/main/resourcesthe directory, create a messages_fr.propertiesresource file named to store French internationalized messages:

greeting.message=Bonjour, le Monde!

Configure internationalization parser

Configuring internationalization parsers in Spring MVC is very simple. src/main/java/com/example/demoCreate a WebConfigconfiguration class in the package called:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import java.util.Locale;

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    
    

    @Bean
    public LocaleResolver localeResolver() {
    
    
        AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
        resolver.setDefaultLocale(Locale.US); // 设置默认语言
        return resolver;
    }
}

In the above code, we create a WebConfigconfiguration class to configure the internationalization parser. AcceptHeaderLocaleResolverThe headers of the client request are parsed Accept-Languageto determine the client's preferred language. You can resolver.setDefaultLocale()set the default language using .

Create controller

src/main/java/com/example/demoCreate a controller class in the package called HelloController:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {
    
    

    private final MessageSource messageSource;

    @Autowired
    public HelloController(MessageSource messageSource) {
    
    
        this.messageSource = messageSource;
    }

    @GetMapping("/hello")
    public String hello(Model model) {
    
    
        String greeting = messageSource.getMessage("greeting.message", null, LocaleContextHolder.getLocale());
        model.addAttribute("greeting", greeting);
        return "hello";
    }
}

In the above code, we create one HelloControllerwhich is injected with MessageSourcethe text used to get the localization. In hellothe method we use messageSource.getMessage()to get the message and add it to the model.

Create a Thymeleaf template

Under src/main/resources/templatesthe directory, create a hello.htmlThymeleaf template named:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello Spring MVC</title>
</head>
<body>
    <h1 th:text="${greeting}"></h1>
</body>
</html>

In the above template, we use Thymeleaf's th:textproperties to render text.

Run application

Now you can run the app

program. Use Maven command:

mvn spring-boot:run

Your Spring MVC application will start and run on the default port (usually 8080).

Visit the internationalization page

Access it using a browser http://localhost:8080/helloand you will see a page that says "Hello, World!" or "Bonjour, le Monde!" depending on the preferred language of your browser settings.

Summarize

This article explains how to handle internationalization and localization needs in Spring MVC. Spring MVC provides rich support, including resource files, internationalization parsers, message sources, and tag libraries, allowing developers to easily build multilingual applications.

The above is a simple example that demonstrates how to handle internationalization and localization in Spring MVC. In actual applications, you can create more resource files and adjust configurations and templates according to your needs. I hope this article will be helpful to you and give you a better understanding of internationalization and localization processing in Spring MVC.

Guess you like

Origin blog.csdn.net/2301_77835649/article/details/133440914