js+java+spring国际化

------------------------------*.js--------------------------------------------------

  alert(hibu.msg["alert.invalid.validate"]);

-----------------------------------*.jsp---------------------------------------------

<!DOCTYPE html>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<%
    String protocol = request.getProtocol().toLowerCase().split("/")[0];
    request.setAttribute("protocol", protocol);
%>
<html>
<head>
<title><spring:message code='eform.title'/></title>

<c:import url="../common/commonHead.jsp"></c:import>

<script type="text/javascript" src="${pageContext.request.contextPath}/js/.../*.js"></script>

.......

-------------------------\web\WEB-INF\jsp\common\commonHead.jsp--------------------------------------------------------

------------------------------------------------\web\js\common\common.js----------------------------------------------------------------------

var hibu = {
    /*validetors*/
    /**
     * @param cityState eg, boston, MA
     * @return cityBean/false
     */
    validateCity : function(cityState, noWarning, seId){
        if(cityState){
            var cb;
            var array = cityState.split(",");
            var errorMsg = hibu.msg["alert.invalid.validateCity"];
            errorMsg = errorMsg.replace(/###/, cityState);
            if(array.length !== 2){
                if(!noWarning){
                    alert(errorMsg);
                }
                return false;
            }else{
                if(seId == "undefined"){
                    seId = 2;
                }
                $.ajax({
                     url: "../geoTargetArea/validateCity.htm",
                     type: 'POST',
                    dataType: 'json',
                     data: {cityState : cityState, seId : seId},
                     async: false,
                     success: function(cityBean){
                         if(cityBean != null){
                             cb = cityBean;
                        }else{
                            cb = false;
                        }
                    },
                    error: function(){
                        cb = false;
                    }
                 });
                if(!cb && !noWarning){
                    alert(errorMsg);
                }
                return cb;
            }
        }else{
            return false;
        }
    } ,
    validateUrlFormat : function(url){
        if(!url || !$.trim(url)){
            return false;
        }
        var _boolean = false;
        $.ajaxRequest({
            url: "../budgetEstimate/validateURL.htm",
            data: {url: url},
            async: false,
            success: function(data){
                _boolean = data;
            }
        });
        return _boolean;
    },
    validateZipCode : function(zip, countryCode){// countryCode optional
        if(!zip || !countryCode){
            return false;
        }
        var _boolean = false;
        $.ajaxRequest({
            url: "../geoTargetArea/validateZipCode.htm",
            data: {zipCode: zip, countryCode: countryCode},
            async: false,
            success: function(data){
                _boolean = data;
            }
        });
        return _boolean;
    },
    scrollTo: function (target) {
        if(target && $(target) && $(target).offset()){
            var _offsetTop = $(target).offset().top;
            $(window).scrollTop(_offsetTop);
        }
    },
    msg:{},// getMessageList.htm?name=hibu.msg
    loginUser: {// getLoginUserCountryCode.htm?name=hibu.loginUser

        countryCode: null ,
        countryList: []
    },

    isSpanishUser: function(){
        return (hibu.loginUser.countryCode == "ES");
    },
    getCurrencySymbol: function(){
        return (hibu.loginUser.countryCode == "ES")? "\u20ac" : "$";
    },
    convertKm2Miles: function(km){
         return Math.round(km * 0.62);
    },
    getCurrencySymbol: function(){
        return (hibu.loginUser.countryCode == "ES")? "\u20ac" : "$";
    },
    convertMiles2Km: function(miles){
        return Math.round(miles * 1.61);
   },

    eformProductType: {
        SEARCH: "Search",
        DISPLAY: "Display"
    },
    searchEngineType: {
        GOOGLE: 2,
        IPromote: 15
    }
};

$.extend($, {
    ajaxJson : function(options){
        var ops = {
            url: "",
            type: 'POST',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            cache: false,
            processData:false,
            loadingMessage: hibu.msg["load.text.loading"],
            modal: false
        };
        $.extend(ops, options);
        if(typeof ops.data == "object"){
            ops.data = JSON.stringify(ops.data);
        }
        $.ajax(ops);
    },
    ajaxRequest : function(options){
        var ops = {
            url: "",
            type: "POST",
            dataType: "json",
            cache: false,
            traditional: true,
            loadingMessage: hibu.msg["load.text.loading"],
            modal: false
        };
        $.extend(ops, options);
        $.ajax(ops);
    }
});

/**
 * common initialization function
 */
$().ready(function(){
    
    /*initialize placehoder for IE*/
    if ("placeholder" in document.createElement("input")) {
        return;
    } else {
        $.watermark.options.hideBeforeUnload = false;
        $("[placeholder]").each(function () {
            $(this).watermark($(this).attr("placeholder"), {
                className: "placehoder"
            });
        });
    }
});

function initAjaxLoader(){
    if($(".loader-modal").length == 0){
        var loader = $("<div class='loader-modal'><div class='loader-content'></div></div>");
        $("body").append(loader);
    }
    $(document).ajaxSend(function( event, request, settings ) {
        if(settings.modal){
            $(".loader-modal").show();
            //according to the UX feedback "Consistent 'loading' or 'Working' treatment. This is the best one"
            //change to "Loading..."
            //$(".loader-content").html(settings.loadingMessage);
            $(".loader-content").html(hibu.msg["load.text.loading"]);
        }
    });
    $(document).ajaxStop(function( event, request, settings ) {
        $(".loader-modal").hide();
    });
}

function randomStr(){
    return String(Math.random()).replace("\.", "");
}
/**
 * <input type="hidden" id="requestID" name="requestID" value="${param.requestID}">
 * @param key
 * @return {*}
 */
function getUrlParam(key) {
    var args = window.location.href.split("?");
    if (args.length > 1) {
        var params = args[1].split("&");
        var requestParam = new Array();
        $(params).each(function (i, value) {
            var pos = value.indexOf('=');
            if (pos > 0) {
                var key = value.substring(0, pos);
                var val = value.substring(pos + 1).replace("#", "");
                if ($.isArray(requestParam[key])) {//push val
                    requestParam[key].push(val);
                } else if (requestParam[key]) {//convert to array
                    var firstVal = requestParam[key];
                    requestParam[key] = [firstVal, val];
                } else {//set val
                    requestParam[key] = val;
                }
            }
        });
        return requestParam[key];
    }
}

function bindEventForExpandArea(expandBtn, expandArea, url, initCallback, expandCallBack) {
    initCallback = (typeof initCallback === "function") ? initCallback : function(){};  
    expandCallBack = (typeof expandCallBack === "function") ? expandCallBack : function(){};  
    $(expandBtn).click(function () {
        var me = this;
        if ($(expandArea).html() == "" && url != "") {
            $.ajax({
                url: url,
                success: function (data) {
                    $(expandArea).html(data);
                    if (!me.initialized) {
                        me.initialized = true;
                        initCallback();
                    }
                    showOrHideExpandArea($(expandArea), $(expandBtn), expandCallBack);
                }
            });
        } else {
            showOrHideExpandArea($(expandArea), $(expandBtn), expandCallBack);
        }
    });
    if($(expandArea).html()){
        var me = $(expandArea).get(0);
        if (!me.initialized) {
            me.initialized = true;
            initCallback();
        }
    }
}

function showOrHideExpandArea(ele, button, after) {
    if ($(button).hasClass("expandBtn")) {
        return showExpandArea(ele, button, after);
    } else {
        return hideExpandArea(ele, button, after);
    }
}

function showExpandArea(ele, button, after) {
    after = after || function(){};
    function show(){
        $(".expandedBtn").not(button).removeClass("expandedBtn").addClass("expandBtn");
        $(button).removeClass("expandBtn").addClass("expandedBtn");
        $(ele).slideDown("normal", function(){
            hibu.scrollTo(button);
            after(true);
        });
    }
    var expandAreas = $(".expandArea:visible").not(ele);
    if(expandAreas.length > 0){
        //close other expanded area
        expandAreas.slideUp("fast", show);
    }else{
        show();
    }
    return true;
}

function hideExpandArea(ele, button, after) {
    after = after || function(){};
    $(button).removeClass("expandedBtn").addClass("expandBtn");
    $(ele).slideUp(function(){
        after(false);
    });
    return false;
}
// log
function log(obj, title) {
    if(console && console.debug){
        if(title){
            console.debug(obj, title);
        }else{
            console.debug(obj);
        }
    }
}

function validatePhone(phone){
    var phoneNumber = hibu.msg["common.regex.phoneNumber"];
    if(eval(phoneNumber).test($.trim(phone))){
        return true;
    }else {
        return false;
    }
}
function validateEmail(email){
    if($.trim(email).toUpperCase().match(hibu.msg["common.regex.email"])){
        return true;
    }else{
        return false;
    }
}

function toLengthAndPad(text, length) {
    if (text == null || text == undefined || length == null || length == undefined) return text;
    if (text.length <= length) return text;
    return text.substring(0, length - 1) + "...";
}

function formatMoney(string) {
    return string.replace(eval(hibu.msg["betResults.regex.money"]), hibu.msg["betResults.text.formatMoney"]);
}

--------------------------------------------------CommonControler.java------------------------------------------------------------

@Controller
@RequestMapping(value = "/common")
public class CommonController extends AbstractController {
    @Autowired
    private BudgetEstimateService budgetEstimateService;

    @RequestMapping(value = "/getMessageList.htm", method = RequestMethod.GET)
    @ResponseBody
    public String getMessageList(Locale locale, @RequestParam(defaultValue = "hibu.i18n") String name) {
        Map<String, String> settings = getMessages(locale);
        String jsonData = JSONObject.fromObject(settings).toString();
        jsonData = String.format(";%s=%s;", name, jsonData);
        return jsonData;
    }

    @RequestMapping(value = "/getLoginUserCountryCode.htm", method = RequestMethod.GET)
    @ResponseBody
    public String getLoginUserCountryCode(Locale locale,
                                          @RequestParam(defaultValue = "hibu.loginUser")
                                          String name,
                                          HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("countryCode", locale.getCountry());
        map.put("countryList", budgetEstimateService.getCountryCodeListByLanguage(locale.getLanguage()));
        String jsonData = JSONObject.fromObject(map).toString();
        jsonData = String.format(";%s=%s;", name, jsonData);
        return jsonData;
    }

    @RequestMapping(value = "/blank.htm", method = RequestMethod.GET)
    public String getBlankPage(Model model, HttpServletRequest request) {
        return "common/blank";
    }
}


package com.yellowbook.presentation.common.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;

import java.util.*;

public abstract class AbstractController {
    public static final String MESSAGE_SOURCE_BASE_NAME = "messages";
    @Autowired
    private MessageSource messageSource;

    protected String getMessage(String key, Locale locale, String... args) {
        return messageSource.getMessage(key, args, locale);
    }

    protected Map<String, String> getMessages(Locale locale) {
        Map<String, String> settings = new HashMap<String, String>();
        Set<String> messages = ResourceBundle.getBundle(MESSAGE_SOURCE_BASE_NAME, locale).keySet();
        for (String key : messages) {
            String value = messageSource.getMessage(key, null, locale);
            settings.put(key, value);
        }
        return settings;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值