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.
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:
-
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.
-
Locale parsing: Spring MVC
LocaleResolver
parses the language and region information requested by the client through the interface. By default, it usesAccept-Language
a header to determine the client's preferred language, but you can customize itLocaleResolver
to suit your specific needs. -
Source: Spring MVC provides
MessageSource
interfaces to load and manage resource files. You can call this in your codeMessageSource
to get the localized text. -
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.xml
the 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/resources
the directory, create a messages.properties
resource file named to store the default internationalized messages:
greeting.message=Hello, World!
In src/main/resources
the directory, create a messages_fr.properties
resource 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/demo
Create a WebConfig
configuration 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 WebConfig
configuration class to configure the internationalization parser. AcceptHeaderLocaleResolver
The headers of the client request are parsed Accept-Language
to determine the client's preferred language. You can resolver.setDefaultLocale()
set the default language using .
Create controller
src/main/java/com/example/demo
Create 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 HelloController
which is injected with MessageSource
the text used to get the localization. In hello
the method we use messageSource.getMessage()
to get the message and add it to the model.
Create a Thymeleaf template
Under src/main/resources/templates
the directory, create a hello.html
Thymeleaf 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:text
properties 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/hello
and 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.