SpringBoot怎么实现国际化
SpringBoot怎么实现国际化
这篇文章主要介绍了SpringBoot怎么实现国际化的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot怎么实现国际化文章都会有所收获,下面我们一起来看看吧。
一、前言
国际化这个功能可能我们不常用,但是在有需要的地方还是必须要上的,今天就来看一下怎么在我们的web开发中配置国际化,让我们的网站可以根据语言来展示不同的形式。
二、国际化配置
2.1 springboot中的自动配置
springboot已经自动配置好了管理国际化资源文件的组件:
@ConfigurationProperties(prefix="spring.messages")publicclassMessageSourceAutoConfiguration{/***Comma-separatedlistofbasenames(essentiallyafully-qualifiedclasspath*location),eachfollowingtheResourceBundleconventionwithrelaxedsupportfor*slashbasedlocations.Ifitdoesn'tcontainapackagequalifier(suchas*"org.mypackage"),itwillberesolvedfromtheclasspathroot.*/privateStringbasename="messages";//我们的配置文件可以直接放在类路径下叫messages.properties;@BeanpublicMessageSourcemessageSource(){ResourceBundleMessageSourcemessageSource=newResourceBundleMessageSource();if(StringUtils.hasText(this.basename)){//设置国际化资源文件的基础名(去掉语言国家代码的)messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(this.basename)));}if(this.encoding!=null){messageSource.setDefaultEncoding(this.encoding.name());}messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);messageSource.setCacheSeconds(this.cacheSeconds);messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);returnmessageSource;}
从上边的源码我们可以看出,我们的国际化资源文件可以直接起名字为messages.properties,springboot就会自动识别,其实相当于在配置文件中添加了一个spring.messages.basename=messages,如果我们指定一个xxx.properties作为国际化文件,那么我们就指定
spring.messages.basename=xxx就可以了,springboot会自动的找到以xxx开头的properties,根据语言和国家代码,找到相应的xxx_zh_CN.properties(中文_中国)、xxx_en_US.properties(英文_美国)来选择其中的资源值作为当前页面中所要渲染的值。
2.2 添加资源文件
我们新建一个名称为i18n的文件夹,在里边添加3个配置文件,分别是login.properties(默认无语言选择时的配置),login_zh_CN.properties(中文语言配置),login_en_US.properties(英文语言配置),默认的格式为:文件名_区域_语言.properties;当我们这样命名生成文件后,IDEA也会帮我们识别这是个国际化配置包,自动转换成如下的模式,上边附带一个Resource Bundle 'login'的文件夹,右键在这个文件夹上点击,就可以方便的添加其他语言的配置:
分别在三个配置文件中写入配置:
login.properties:
login.btn=登陆~login.password=密码~login.remember=记住我~login.tip=请登陆~login.username=用户名~
login_zh_CN.properties:
login.tip=请登录login.username=用户名login.password=密码login.btn=登录login.remember=记住我
login_en_US.properties:
login.tip=Pleasesigninlogin.username=Usernamelogin.password=Passwordlogin.btn=Signinlogin.remember=RememberMe
然后我们的主配置文件application.properties中添加如下配置,启用我们自定义的资源文件:
spring.messages.basename=i18n.login
2.3 添加登录页面
这里我们以之前的thymeleaf语法来添加一个登录页面来进行测试:
<!DOCTYPEhtml><htmllang="en"xmlns:th="http://www.thymeleaf.org"><head><metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1,shrink-to-fit=no"><metaname="description"content=""><metaname="author"content=""><title>SigninTemplateforBootstrap</title><!--BootstrapcoreCSS--><linkth:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}"rel="stylesheet"><!--Customstylesforthistemplate--><linkth:href="@{/asserts/css/signin.css}"rel="stylesheet"></head><bodyclass="text-center"><formclass="form-signin"action="dashboard.html"th:action="@{/user/login}"method="post"><imgclass="mb-4"th:src="@{/asserts/img/bootstrap-solid.svg}"src="asserts/img/bootstrap-solid.svg"alt=""width="72"height="72"><h2class="h4mb-3font-weight-normal"th:text="#{login.tip}">Pleasesignin</h2><!--判断--><pstyle="color:red"th:text="${msg}"th:if="${not#strings.isEmpty(msg)}"></p><labelclass="sr-only"th:text="#{login.username}">Username</label><inputtype="text"name="username"class="form-control"placeholder="Username"th:placeholder="#{login.username}"required=""autofocus=""><labelclass="sr-only"th:text="#{login.password}">Password</label><inputtype="password"name="password"class="form-control"placeholder="Password"th:placeholder="#{login.password}"required=""><divclass="checkboxmb-3"><label><inputtype="checkbox"value="remember-me"/>[[#{login.remember}]]</label></div><buttonclass="btnbtn-lgbtn-primarybtn-block"type="submit"th:text="#{login.btn}">Signin</button><pclass="mt-5mb-3text-muted">©2017-2018</p><aclass="btnbtn-sm"th:href="@{/index.html(lang='zh_CN')}">中文</a><aclass="btnbtn-sm"th:href="@{/index.html(lang='en_US')}">English</a></form></body></html>
#{login.username} 会直接从国际化的资源文件中取到我们所配置的值,根据不同的语言会切换为不同的语言配置,默认是根据浏览器的语言来判断的,我们可以按照以下方式来设置浏览器的语言来查看效果,在谷歌浏览器的设置里边搜索语言,然后添加一个英文语言,设置语言的顺序来设置首选语言,如下所示:
我们也可以查看浏览器发送的请求头部分来确定语言是否 设置成功:
2.4 自定义语言文化解析器
从上边我们可以看出,默认的是从请求头中解析语言文化的,我们可以设置自己的解析器,比如访问页面的查询参数中来解析语言,下边是我们的登录页面,我们可以添加两个按钮,当点击按钮的时候,重新跳转index.html页面,并附带上一个lang的参数:
可以查看网页源代码,我们生成的链接:
html关键代码,用thymeleaf生成,也可以自己手写:
<buttonclass="btnbtn-lgbtn-primarybtn-block"type="submit"th:text="#{login.btn}">Signin</button><pclass="mt-5mb-3text-muted">©2017-2018</p><aclass="btnbtn-sm"th:href="@{/index.html(lang='zh_CN')}">中文</a><aclass="btnbtn-sm"th:href="@{/index.html(lang='en_US')}">English</a>
添加我们自己的解析器MyLocaleResolver,从请求参数中获取lang,根据lang的值来设置不同的Locale:
packagecom.example.demo.component;importorg.springframework.util.StringUtils;importorg.springframework.web.servlet.LocaleResolver;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.util.Locale;publicclassMyLocaleResolverimplementsLocaleResolver{@OverridepublicLocaleresolveLocale(HttpServletRequesthttpServletRequest){Stringlang=httpServletRequest.getParameter("lang");Localelocale=Locale.getDefault();if(!StringUtils.isEmpty(lang)){String[]parts=lang.split("_");locale=newLocale(parts[0],parts[1]);}returnlocale;}@OverridepublicvoidsetLocale(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse,Localelocale){}}
在WebConfig添加如下代码,把这个MyLocaleResolver添加到容器中去,springboot发现到有LocaleResolver的新实例,就会用这个解析器:
重新编译启动就可以了,点击不同语言跳转不同链接,显示不同的语言:
关于“SpringBoot怎么实现国际化”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“SpringBoot怎么实现国际化”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注恰卡编程网行业资讯频道。
推荐阅读
-
springboot实现基于aop的切面日志
本文实例为大家分享了springboot实现基于aop的切面日志的具体代码,供大家参考,具体内容如下通过aop的切面方式实现日志...
-
SpringBoot定时任务功能怎么实现
-
SpringBoot中的@Import注解怎么使用
-
SpringBoot整合Lombok及常见问题怎么解决
-
springboot图片验证码功能模块怎么实现
-
Springboot+SpringSecurity怎么实现图片验证码登录
-
SpringBoot注解的知识点有哪些
SpringBoot注解的知识点有哪些这篇“SpringBoot注...
-
SpringBoot2.x中management.security.enabled=false无效怎么解决
-
springboot怎么禁用某项健康检查
springboot怎么禁用某项健康检查今天小编给大家分享一下sp...
-
SpringBoot2怎么自定义端点