Spring mvc i18n國際化的簡單demo
阿新 • • 發佈:2018-11-01
在渲染檢視的xml檔案中,配置一個i18nBean
@Controller
package com.oukele.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.LocaleResolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.rmi.registry.LocateRegistry;import java.util.Locale; @Controller public class xxxController { //將 i18n 注入容器中 @Autowired private LocaleResolver localeResolver; /** * 請求url:/cl * 請求方式:GET * 返回結果:得到一個檢視 * */ @RequestMapping(path = "/cl",method = RequestMethod.GET) public String index(){return "index"; } /** * 請求url:/cl/xxx * 請求方式:GET * 根據url帶回來的引數,改變要呼叫語言資原始檔 * 重定向 * */ @GetMapping("/cl/{loc}") public String changeLocale(@PathVariable("loc") String localseStr, HttpServletRequest request, HttpServletResponse response){ Locale locale =new Locale(localseStr); localeResolver.setLocale(request,response,locale); return "redirect:/cl"; } }
頁面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <html> <head> <title><spring:message code="title" /></title> </head> <body> <div> <spring:message code="page.cl" /> <br> <a href="/cl/zh">中文</a> <a href="/cl/en">English.</a> <a href="/cl/jp">日本</a> <br><br> </div> <div style="border: 1px solid red;margin: auto;height: 300px;text-align: center"> <spring:message code="context.cl" /> </div> </body> </html>
messages中的語言資源包。
語言資源包:
xxxx_en.properties:
title=This is a test
user.id=Emp Id
user.name=Emp Name
user.sal=Emp Salary
context.cl=When spring sleeps, birds are heard everywhere.At night comes rain and wind.
page.cl=Click to change current language:
xxxx_zh.properties:
title=這是一個測試
user.id=使用者編號
user.name=使用者姓名
user.sal=使用者工資
context.cl=春眠不覺曉,處處聞啼鳥。夜來風雨聲,花落知多少。
page.cl=點選切換語言:
xxxx_jp.properties:
title=人気
user.id=ioujojfasojf
user.name=aaaaaaaaaaaaaaa.
user.sal=oh, noooooh.
context.cl=春の眠りがついていて,あちこちで鳴く鳥を聞いている。夜は風雨の音がして,花がどれくらい落ちたかを知る。
page.cl=切り替え言語
結果:
一個菜鳥的筆記,路過的大佬見諒哈。