zoukankan      html  css  js  c++  java
  • Spring中后台字符串国际化

      1.在工程的资源文件夹(source folder)中建立三个properties文件:messages.properties(默认)、messages_zh_CN.properties(中文)、messages_en_US.properties(英文)。

      properties文件中的字符串资源采用键值对的格式填写信息,如下:

        HelloWorld=问候语:@0 问候时间:@1;

      2.获取国际化字符串的工具类 UniversalMsg

      

    package com.luxl.action;
    
    import java.util.Locale;
    import java.util.ResourceBundle;
    
    /**
     * @description 用于获取国际化字符串
     * @author luxl
     *
     */
    public class UniversalMsg {
        //下面中的参数messages是资源文件的起始字段,但要求资源文件在资源文件夹下,如果是在资源文件夹下的某个文件夹下,比如i18n,则参数值应该为为i18n/messages
        private static ResourceBundle rb_ch = ResourceBundle.getBundle("messages",Locale.CHINA);
        
        private static ResourceBundle rb_en = ResourceBundle.getBundle("messages", Locale.US);
        
        /**
         * @description 获取key的国际化字符串
         * @param locale 语种:中文(Locale.CHINA),英文(Locale.US)
         * @param key 要获取的字符串的key
         * @return
         * @throws Exception
         */
        public static String getString(Locale locale, String key) throws Exception{
            if(key!=null && (!key.trim().isEmpty())){
                if(locale.equals(Locale.CHINA)){
                    return rb_ch.getString(key);
                }else{
                    return rb_en.getString(key);
                }
            }else{
                return "";
            }
        }
        
        /**
         * @description 获取key的中文字符串
         * @param key
         * @return
         * @throws Exception
         */
        public static String getString(String key) throws Exception{
            if(key!=null && (!key.trim().isEmpty())){
                return rb_ch.getString(key);
            }else{
                return "";
            }
        }
    
    }

      3.应用举例:

    try {
        String us_msg;
        us_msg = UniversalMsg.getString(Locale.US,"HelloWorld");
        us_msg = us_msg.replaceAll("@0", helloWorld.getMsg());
        us_msg = us_msg.replaceAll("@1", Calendar.getInstance().getTime().toString());
        System.out.println(us_msg);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        System.out.println("error");
        e.printStackTrace();
    }  

    注:如果没有找到相对应key的字符串,会抛出异常。

  • 相关阅读:
    php中除法取整的方法(round,ceil,floor)
    ajax 实现修改功能
    ueditor PHP版本使用方法
    $.ajax json 在本地正常 上传服务器不正常
    Web常见几种攻击与预防方式
    PHP使用Session遇到的一个Permission denied Notice解决办法
    VUE引入模块之import xxx from 'xxx' 和 import {xxx} from 'xxx'的区别
    JS事件委托或者事件代理原理以及实现
    JS 一次性事件问题
    原生JS 和 JQ 获取滚动条的高度,以及距离顶部的高度
  • 原文地址:https://www.cnblogs.com/ScorchingSun/p/3979418.html
Copyright © 2011-2022 走看看