准备
页面国际化创建的文件
代码
/页面国际化 public class MyLocalResolver implements LocaleResolver { //解析请求 @Override public Locale resolveLocale(HttpServletRequest request) { String language =request.getParameter("l"); Locale locale =Locale.getDefault();//如果没有就使用默认的 //如果有 if(!StringUtils.isEmpty(language)){ //zh_CN(从_分离)(国家,地区) String[] split =language.split("_"); System.out.println(split[0]+split[1]); locale =new Locale(split[0],split[1]); } return locale; } @Override public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) { } }
//扩展springMVC,也就是重写WebMvcConfigurer里面的方法 @Configuration public class MyMvcConfig implements WebMvcConfigurer { //让自定义国际化组件生效,也就是注入到spring里 @Bean public LocaleResolver localeResolver(){ return new MyLocalResolver(); } }
@Controller public class one { @RequestMapping("/one") public String one(Model model) { model.addAttribute("msg", "<h1>ffl</h1>"); // Arrays.asList,把数组转化成一个集合 model.addAttribute("users", Arrays.asList("f","gg","hh")); return "one"; } @RequestMapping({"/", "/index"}) public String index(Model model) { return "index"; } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <title>首页</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <form> <h1 th:text="#{login.tip}">please login in</h1> <div> <input type="password" th:placeholder="#{login-password}" required=""> <label> <input type="checkbox" value="remember me">[[#{login.remember}]] </label> </div> <button type="submit">[[#{login.btn}]]</button> <a th:href="@{/index(l='zh_CN')}">中文</a> <a th:href="@{/index(l='en_US')}">English</a> </form> </body> </html>
注意点