首页 > 编程语言 > 详细

Spring mvc i18n国际化的简单demo

时间:2018-11-01 11:09:35      阅读:162      评论:0      收藏:0      [点我收藏+]

在渲染视图的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=切り替え言語

 

 结果:

技术分享图片

技术分享图片

技术分享图片

一个菜鸟的笔记,路过的大佬见谅哈。

Spring mvc i18n国际化的简单demo

原文:https://www.cnblogs.com/oukele/p/9887330.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!