spring的多语言怎么实现?
1.创建springboot项目,并配置application.properties文件
spring.messages.basename=messages
spring.messages.encoding=UTF-8
spring.messages.fallback-to-system-locale=falsespring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
2.resources路径下新建messages.properties文件
messages.properties、messages_zh_CN.properties文件
3.新建config类并实现WebMvcConfigurer类,设置默认语言为英语
@Configuration
public class I18nConfig implements WebMvcConfigurer {@Beanpublic LocaleResolver localeResolver() {SessionLocaleResolver resolver = new SessionLocaleResolver();resolver.setDefaultLocale(Locale.ENGLISH);return resolver;}
}
4.编写controller类接收请求
package com.test;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;/*** @Description TODO* @Date 2025/5/29 18:09* @Version 1.0*/
@Controller
public class HomeController {private final MessageSource messageSource;@Autowiredpublic HomeController(MessageSource messageSource) {this.messageSource = messageSource;}@GetMapping("/")public String home(Model model) {String message= messageSource.getMessage("message",null,LocaleContextHolder.getLocale());model.addAttribute("message", message);return "home";}}
5.在resources下新建templates目录并添加home.html文件
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title th:text="#{login.title}">Login</title>
</head>
<body>
<h1 th:text="${message}">Welcome</h1>
<p th:text="#{user.greeting('LiLi')}">Hello, User</p>
<div><a href="?lang=en">English</a> |<a href="?lang=zh-CN">中文</a> |
</div>
</body>
</html>