当前位置: 首页 > java >正文

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>

http://www.xdnf.cn/news/9757.html

相关文章:

  • OSI 七大层详解
  • vue element日期范围选择器只能选择指定天数内的
  • shell脚本实现字符串子网掩码转为位数
  • mqtt协议连接阿里云平台
  • 基于多模态脑电、音频与视觉信号的情感识别算法【Nature核心期刊,EAV:EEG-音频-视频数据集】
  • Deepseek应用技巧-Dify本地化搭建合同审批助手
  • Delphi 导入excel
  • 【东枫科技】KrakenSDR 测向快速入门指南
  • Vision Transformer网络结构
  • 【穷举】数字方格
  • 文件系统与文件管理:从磁盘到内核的全链路解析
  • 高效工具-tldr
  • 网络安全的守护者:iVX 如何构建全方位防护体系
  • 镍钯金PCB有哪些工艺优势?
  • 五、web安全--XSS漏洞(2)--XSS相关payload
  • 《Discuz! X3.5开发从入门到生态共建》第3章 Discuz! X3.5 核心目录结构解析-优雅草卓伊凡
  • Parsel深度解析:从入门到高阶的网页数据抓取艺术
  • python同步mysql数据
  • WPS 免登录解锁编辑
  • 安全访问 std::tuple 的容错方法及气象领域应用
  • R3GAN利用配置好的Pytorch训练自己的数据集
  • Vue-Router中的三种路由历史模式详解
  • MCP入门实战(极简案例)
  • eNSP企业综合网络设计拓扑图
  • linux有效裁剪视频的方式(基于ffmpeg,不改变分辨率,帧率,视频质量,不需要三方软件)
  • 挖洞日记 | Js中的奇妙旅行
  • AXI 协议补充(二)
  • 从本地到云端:Code App+SSH协议在iPad开发中的性能优化实战
  • VLC-QT 网页播放RTSP
  • 6个月Python学习计划 Day 8 - Python 函数基础