19.0、springboot-国际化以及404错误解决
第一步:在resources文件夹下的i18n文件夹下创建三个properties文件如下图所示:
第二步:点击左下角的Resource Bundle进入可视化配置界面如下:
第三步:创建自定义property key
第四步:配置一下内容
我们双击shift按键,搜索MessageSourceAutoConfiguration.java这个类可以看到,在配置文件中应该用spring.message这样来配置
第五步:在application.properties配置文件中添加一下配置即可
#配置一下我们配置文件的位置
spring.messages.basename=i18n.login
双击shift按键搜索WebMvcAutoConfiguration.java可以看到一个叫做LocaleResolver的地区解析,如果我们手动配置了这些就会使用用户配置的,如果没有配置就会使用默认的
第六步:写好一个登录界面index.html文件
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1 th:text="#{login.tip}"></h1>
<form th:action="@{/gotomanager}">
<input type="text" th:placeholder="#{login.username}" /><br/>
<input type="password" th:placeholder="#{login.password}" /><br/>
<input type="submit" th:value="#{login.btn}"><br/>
</form>
<a th:href="@{/index.html(l='zh_CN')}">中文</a>
<a th:href="@{/index.html(l='en_US')}">英文</a>
</body>
</html>
第七步:我们自己在config文件夹里来写一个地区解析器
MyLocaleResolver.java文件
package com.hkl.config;
import org.apache.tomcat.jni.Local;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class MyLocaleResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取请求中的语言参数
String language = request.getParameter("1");
Locale locale = Locale.getDefault();//如果没有就使用默认的;
//如果请求的链接了国际化的参数
if(!StringUtils.isEmpty(language)) {
//zh_CN
String[] split = language.split("_");
//国家,地区
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
第八步:再把这个类放到容器里去才能生效:
MyMvcConfig.java文件
package com.hkl.config;
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.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//扩展 springmvc dispatchservlet
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
//自定义的国际化组件就生效了!
@Bean
public LocaleResolver localeResolver() {
return new MyLocaleResolver();
}
}
再次启动springboot即可
但是在这里一直报404的错误原因如下:
因为我之前在而配置文件视图解析器中是这样的配置:
改为如下图配置即可: