亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Spring mvc基于Cookie的語言國際化處理

標簽:
Java

1. 首先要在spring mvc的配置文件当中对语言的国际化进行配置,代码如下:

    <!-- 语言国际化 -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <!-- 国际化信息所在的文件名 -->
        <property name="basename" value="i18n.message" />
    <!--    如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称 -->
        <property name="useCodeAsDefaultMessage" value="true" />
    </bean>

    <mvc:interceptors>
        <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
    </mvc:interceptors>
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />

2. 在项目src下新建一个i18n的包,包下新建两个名为:message_zh_CN.properties和message_en_US.properties的properties中英文配置文件,message_zh_CN.properties文件的内容为:

    language1=中文
    language2=英文

    username=用户名
    password=密码
    sex=性别
    email=邮箱
message_en_US.properties文件的内容为:

    language1=Chinese
    language2=English

    username=Username
    password=Password
    sex=Sex
    email=Email

3. 在需要国际化的jsp页面中加入一个标签库:<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>,把需要国际化的文字改成一个spring标签:

    <spring:message code="username" />
    <spring:message code="password" />
    <spring:message code="sex" />
    <spring:message code="email" />

spring标签里面的code属性的值就是message_zh_CN.properties和message_en_US.properties对应的名字

4. 在页面当中加入两个中文切换的链接:

    <a href="${pageContext.request.contextPath }/user/changeLang?langType=zh" ><spring:message code="language1" /></a>
<a href="${pageContext.request.contextPath }/user/changeLang?langType=en" ><spring:message code="language2" /></a>

5. 在Controller控制类当中编写一个国际化的方法,代码如下:

    //基于Cookie的国际化处理
    @RequestMapping(value = "/changeLang")
    public String changeLang(HttpServletRequest request, HttpServletResponse response, Model model, 
            @RequestParam(value = "langType", defaultValue = "zh") String langType) {
        if (!model.containsAttribute("contentModel")) {
            if (langType.equals("zh")) {
                Locale locale = new Locale("zh", "CN");
                (new CookieLocaleResolver()).setLocale(request, response, locale);
            } else if (langType.equals("en")) {
                Locale locale = new Locale("en", "US");
                (new CookieLocaleResolver()).setLocale(request, response, locale);
            } else
                (new CookieLocaleResolver()).setLocale(request, response, LocaleContextHolder.getLocale());
        }
        return "redirect:/user/list";
    }

 至此,基于Cookie的语言国际化处理全部完成,还有基于其他方法实现的国际化处理请参考:SpringMVC学习系列(8) 之 国际化,有兴趣的小伙伴的可以了解一下!

點擊查看更多內容
3人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消