Spring mvc i18n国际化的简单demo

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

 结果:

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

猜你喜欢

转载自www.cnblogs.com/oukele/p/9887330.html