springmvc 国际化

spring-mvc.xml配置文件:

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

controller:

package com.tomtop.portal.ctl;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

@Controller
public class LocaleCtl {
    /**
     * 语言切换
     */
    @RequestMapping(method = RequestMethod.GET, value = "/lang")
    @ResponseBody
    public String lang(HttpServletRequest request) {
        String langType = request.getParameter("langType");
        if (langType.equals("zh_cn")) {
            Locale locale = new Locale("zh", "CN");
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
        } else if (langType.equals("en")) {
            Logger.getLogger(LocaleCtl.class).info("langtype=" + langType);
            Locale locale = new Locale("en", "US");
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
        } else
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,
                    LocaleContextHolder.getLocale());
        return null;
    }
}

新建语言包文件,如图,内容为:somewords=translatedwords

页面中使用:

<spring:message code="welcome"></spring:message>  <!--code为要翻译的信息,配置在语言包中-->

 

posted @ 2015-12-29 20:38  until-u  阅读(222)  评论(0编辑  收藏  举报