我在写一个项目时,国际化语言转换的时候出现了404
但是看到url里面参数确实是传进去了,后来经过调试和查找资料知道了问题出在这里:
静态资源都是默认跳转到static里面,而我们的视图都放在了templates里面
所以想解决这个问题,就要自己创建个自定义跳转。
具体方法:
在config包下建一个MyConfig类
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login.html").setViewName("/login");
}
}
下面是我实现国际化的方法:
1.在config包下创建一个MyLocaleResolver实现LocaleResolver接口。
public class MyLocaleResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
//获取请求中的语言参数链接
String language = httpServletRequest.getParameter("l");
Locale locale = Locale.getDefault();//如果没有使用默认
//如果请求的链接携带了国际化参数
if(!StringUtils.isEmpty(language)){
//en_US
String[] split = language.split("_");
//语言 国家
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
介绍下LocaleResolver:
LocaleResolver的主要作用: 解析Request中的语言标志参数或者head中的Accept-Language参数, 并将解析后的参数保存到指定的域中。
2.在视图中转换路径:
3.自定义Bean,交给spring托管
/*自定义国际化*/
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
现在就可以测试下是否成功了!
中文:
英文:
发现404问题已经解决了!
总结:如果想让springboot自动跳转,就需要把html文件放在static文件下,如果在其他文件夹下,就需要自定义跳转。