1.目录结构和效果图
2.在resources目录下创建i18n资源文件,并写入数据
3.导入config
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class LocaleConfig extends WebMvcConfigurerAdapter {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
// 默认语言
slr.setDefaultLocale(Locale.US);
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
// 参数名
lci.setParamName("lang");
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
4.控制层
@Controller
@RequestMapping("user")
public class LoginController {
@Autowired
private MessageSource messageSource;
/**
* HTML
* @return
*/
@RequestMapping("login")
public String login(){
return "index";
}
/**
* JSP
* @return
*/
@RequestMapping("index")
public String index(Model model){
Locale locale = LocaleContextHolder.getLocale();
model.addAttribute("password", messageSource.getMessage("password", null, locale));
return "login";
}
}
5.jsp页面
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>我是返回的JSP页面</h1>
<a href="/user/index?lang=en_US">English(US)</a>
<a href="/user/index?lang=zh_CN">简体中文</a><br>
<h1>******************************</h1><br>
<spring:message code='userName'/>:<br>
${password}:
<h1>******************************</h1>
</body>
</html>
6.测试链接
http://localhost/user/index