Spring MVC 国际化

  • 原生的国际化处理方式,详见i18n 国际化
  • 以下主要讲解通过Spring MVC的方式实现国际化。

示例一:

  • 页面根据浏览器的语言,返回相对应的语言的文字。
  • 配置文件。声明国际化资源文件,basename为国际化资源文件的基础名。
    <!--  配置国际化  -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="login"/>
        <!-- 支持UTF-8的中文 -->
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
    
  • 国际化资源文件
    在这里插入图片描述
    # login_en_US.properties
    welcome=Welcome to my website!
    username=UserName
    password=Password
    
    # login_zh_CN.properties
    welcome=欢迎来到我的网站!
    username=用户名
    password=密码
    
  • 配置文件中,注册一个视图控制器,若使用请求转发,则无需此组件。(为了让静态资源不绕过Spring MVC)
    <!--  视图控制器,无需在Controller转发,就可以直接进入jsp页面  -->
    <mvc:view-controller path="/login" view-name="login"/>
    
  • 请求页面
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <html>
    <head>
        <title></title>
    </head>
    <body>
    <h1><fmt:message key="welcome"/></h1><br/>
        <fmt:message key="username"/><br/>
        <fmt:message key="password"/><br/>
    </body>
    </html>
    

示例二:

  • 通过点击超链接的方法,切换语言。
  • 重点:通过解析请求参数,根据请求参数设置Locale
  • 方法有三:
    • 自己实现一个 LocaleResolver ,解析请求参数,返回一个Locale
    • 使用 SessionLocaleResolver ,并在请求映射中,解析请求参数,并将 Locale 放在 Session 域中
    • 使用 SessionLocaleResolverLocaleChangeInterceptor 拦截器,一步到位

LocaleResolver

  • 首先,需要解释一下LocaleResolver接口,有两个方法。一般实现resolveLocale即可,该方法通过解析request对象,生成一个Locale对象,并予以返回。setLocale用于设置Locale,在拦截器中会使用到该方法,因此使用拦截器的时候,需要使用一个实现了setLocale的类。
    public interface LocaleResolver {
    	Locale resolveLocale(HttpServletRequest request);
    	void setLocale(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Locale locale);
    
    }
    

实现 LocaleResolver 的方法

  • 配置 messageSource 以及国际化资源文件同上,再此不再赘述。
  • 请求页面。有两个超链接,通过点击超链接,转换语言。
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <html>
    <head>
        <title></title>
    </head>
    <body>
    <%
        request.setAttribute("ctp", request.getContextPath());
    %>
    
    <a href="${ctp}/login?locale=zh_CN">中文</a> | <a href="${ctp}/login?locale=en_US">英文</a> <br/>
    <h1><fmt:message key="welcome"/></h1><br/>
        <fmt:message key="username"/><br/>
        <fmt:message key="password"/><br/>
    </body>
    </html>
    
  • 为了方便,无需再写一个请求映射,在这里写了一个 ViewController,直接url映射到jsp上
    <!--  视图控制器,无需在Controller转发,就可以直接进入jsp页面  -->
    <mvc:view-controller path="/login" view-name="login"/>
    
  • 实现类。请求参数格式为..?locale=语言_国家,如locale=zh_CN
    public class MyLocaleResolver implements LocaleResolver {
      @Override
      public Locale resolveLocale(HttpServletRequest request) {
        String localeStr = request.getParameter("locale");
        if (localeStr == null || "".equals(localeStr))
          return request.getLocale();
        String language = localeStr.split("_")[0];
        String country = localeStr.split("_")[1];
        return new Locale(language, country);
      }
    
      @Override
      public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        throw new UnsupportedOperationException(
                "Cannot change HTTP accept header - use a different locale resolution strategy");
      }
    }
    
  • 配置上面的 LocalResolver
    <bean class="com.du.springmvc.MyLocaleResolver" id="localeResolver"/>
    

使用 SessionLocaleResolver 方法

  • 配置 LocaleResolver
    <bean class="org.springframework.web.servlet.i18n.SessionLocaleResolver" id="localeResolver"/>
    
  • 请求映射
      @RequestMapping("/login2")
      public String login2(HttpServletRequest request, HttpSession httpSession) {
        String localeStr = request.getParameter("locale");
        Locale locale = null;
        if (localeStr == null || "".equals(localeStr)) {
          locale =  request.getLocale();
        } else {
          String language = localeStr.split("_")[0];
          String country = localeStr.split("_")[1];
          locale =  new Locale(language, country);
        }
        httpSession.setAttribute(SessionLocaleResolver.class.getName() + ".LOCALE", locale);
        return "login2";
      }
    
  • 请求页面
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <html>
    <head>
        <title></title>
    </head>
    <body>
    <%
        request.setAttribute("ctp", request.getContextPath());
    %>
    
    <a href="${ctp}/login2?locale=zh_CN">中文</a> | <a href="${ctp}/login2?locale=en_US">英文</a> <br/>
    <h1><fmt:message key="welcome"/></h1><br/>
        <fmt:message key="username"/><br/>
        <fmt:message key="password"/><br/>
    </body>
    </html>
    

使用 LocaleChangeInterceptor 的方法

  • 配置 LocaleResolver
    <bean class="org.springframework.web.servlet.i18n.SessionLocaleResolver" id="localeResolver"/>
    
  • 配置拦截器
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/login"/>
            <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
    
  • 请求页面及其 ViewController 与方法一相同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值