SpringMvc之国际化-yellowcong

springmvc 专栏收录该内容
17 篇文章 0 订阅

国际化处理,通过SpringMvc实现国际化,是一件非常容易的事情。需要涉及到的类有CookieLocaleResolver,在Spring-mvc中配置这个备案,然后 在控制层注入这个对象,调用 setLocale函数,设定语言。通过这个类完成国际化的设定,这样其他的页面只需要一次访问,就永久设定了。推荐大家使用国家化的插件1、PropeEdit 2、JInto

目录结构

messages目录下面是国际化的配置文件
这里写图片描述

后台代码

package com.yellowcong.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

@Controller
@RequestMapping("/test")
public class DemoI18n {
    //语言类型
    private static final String LANGUAGE_TYPE ="language_type";

    //默认的语言
    private static final String LANGUAGE_DEFAULT ="zh_CN";

    @Autowired
    private CookieLocaleResolver resolver;

    /**
     * 设定语言类型
     * @param request
     * @param response
     * @param language
     * @return
     */
    @RequestMapping(value = "/language", method = RequestMethod.GET)
    public String language(HttpServletRequest request,HttpServletResponse response,String language) {
        //将设置的language放到session里面,这样就可以保证访问language方式时候,避免不带参数的问题
        Object type = this.getSession().getAttribute(LANGUAGE_TYPE);

        //都为空的情况设定默认
        if(StringUtils.isEmpty(language)){
            if(type != null ){
                language = type.toString();
            }else{
                language = LANGUAGE_DEFAULT;
            }
        }

        //判断语言类型
        switch (language.toLowerCase()) {
        case "en":
            resolver.setLocale(request, response, Locale.ENGLISH);
            break;
        default:
            resolver.setLocale(request, response, Locale.CHINA);
            break;
        }
        //更新Session里面的数据
        this.getSession().setAttribute(LANGUAGE_TYPE, language);

        return "demo/i18n";
    }

    @RequestMapping("page2")
    public String page2(){
        return "demo/page2";
    }
    /**
     * 获取Session
     * @return
     */
    public HttpSession getSession() {
        // 获取到ServletRequestAttributes 里面有
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取到Request对象
        HttpServletRequest request = attrs.getRequest();
        //获取户Session
        HttpSession session = request.getSession();

        return session;
    }
}

前台代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<head>
<title>xx文章</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<spring:message code="doubi"/>
<spring:message code="game"/>
</body>
</html>

访问结果

这里写图片描述

设定为英文
这里写图片描述

设置为英文后,不带参数,访问照样是没有毛病。
这里写图片描述

环境搭建

我觉得,我得把环境搭建写上,每次做了,都是主要部分的代码,没有 把环境给打上

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>yellowcong</groupId>
    <artifactId>day11_13</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>day11_13 Maven Webapp</name>
    <url>http://maven.apache.org</url>


    <!-- 配置国内比较快的 阿里云的Maven仓库 -->
    <repositories>
        <repository>
            <id>aliyunmaven</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <!-- 共用的配置说明,比如spring版本, 项目名称, jdk版本等 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.2.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!-- Spring  BEGIN-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 导入Spring的orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Slf4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <!-- 配置切面 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!---aspectj 面向切向 -->
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.5</version>
        </dependency>
        <!-- Spring需要的注解 -->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Spring 的测试类 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring  END-->

        <!-- 配置Spring mvc -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- 文件上传  Begin-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- 文件上传  End-->

        <!-- 表单验证 -->
        <dependency>  
            <groupId>org.hibernate</groupId>  
            <artifactId>hibernate-validator</artifactId>  
            <version>4.3.1.Final</version>  
        </dependency>  

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>

        <!-- JSON解析 -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.11</version>
        </dependency>

        <!-- 日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>day11_13</finalName>
    </build>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>demo</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- Spring mvc -->
    <servlet>
        <servlet-name>config</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置Spring mvc,如果不配置,就会默认在wWEB-INF/config-servlet.xml -->
        <init-param>
            <description>spring mvc 配置文件</description>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>config</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- 设定字符编码 -->
    <filter>
        <filter-name>CharacterFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- spring的监听器,可以通过上下文来获取参数 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>

</web-app>

spring-mvc.xml配置文件

这个地方,可以配置默认的语言包,默认当然就是中文啦

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    <mvc:default-servlet-handler/>
    <!-- 通过Annotation 来控制Controller -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <context:component-scan base-package="com.yellowcong.*"/>

    <!-- 配置国际化资源文件路径 -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <!-- 定义消息资源文件的相对路径 -->
            <value>messages/message</value>
        </property>
    </bean>
    <!-- 基于Cookie的本地化解析器 -->
     <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
       <property name="cookieMaxAge" value="604800"/>
       <property name="defaultLocale" value="zh_CN"/>
       <property name="cookieName" value="Language"></property>
     </bean>

    <!-- 将静态文件夹制定到某个特别的文件夹中统一处理
        ** 表示的是文件夹中的子文件夹中的所有类容
        其中location 需要两个 正斜杠
     -->
    <mvc:resources location="/resources/" mapping="/resources/**"/>
        <!-- 配置权限拦截器 -->
        <!-- 当我们的数据访问到 amdin的时候,就会直接调用admin对象 -->
 <!--   <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/user/**"/>
            <mvc:mapping path="/role/**"/>
            <mvc:mapping path="/group/**"/>
            <mvc:mapping path="/attachment/**"/>
            <mvc:mapping path="/reply/**"/>
            <mvc:mapping path="/tabel/**"/>
            <mvc:mapping path="/image/**"/>
            <mvc:mapping path="/info/**"/>
            <mvc:mapping path="/login/stu"/>
            <mvc:mapping path="/admin/**"/>
            <bean class="com.yellowcong.interceptor.UserInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>  --> 
    <!-- 设定访问的名称 和对应的Servlet -->    
    <!-- 配置Multipart,只有设定了才能完成文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 最大文件大小,-1为无限止(-1) -->  
        <property name="maxUploadSize" value="5000000"/>
        <!-- 最大内存大小 (10240)--> 
        <property name="maxInMemorySize" value="10240"/>
        <!-- 设置编码 ,默认编码 (ISO-8859-1)-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->  
        <property name="resolveLazily" value="true"/>    
    </bean>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 3.0.5后默认加上了jstl的属性配置.这个就是默认的配置 -->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <!-- 设定前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- 设定后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 配置全局异常 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
            <!-- 
                <prop key="com.yellowcong.exception.UserException">error</prop>
                <prop key="java.lang.RuntimeExceptio">error</prop>
             -->
            </props>
        </property>
    </bean>
</beans>

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    ">
    <!-- 自动扫描(自动注入) -->
    <context:annotation-config />
    <context:component-scan base-package="com.yellowcong.*" />

    <!--导入mybatis的配置 -->
    <import resource="spring-mvc.xml"/>

</beans>

国际化配置文件

message_en.properties(英文)

age=age
doubi=doubi
game=game
name=name
test=test

message_zh_CN.properties(中文)

age=\u5e74\u7eaa
doubi=\u9017\u903c
game=\u6e38\u620f
name=\u540d\u79f0
test=\u6d4b\u8bd5

参考文章

http://www.xdemo.org/spring-i18n/
https://www.cnblogs.com/liukemng/p/3750117.html

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值