首页 > 其他分享 >SpringMVC学习系列(8) 之 国际化

SpringMVC学习系列(8) 之 国际化

时间:2023-05-29 13:02:12浏览次数:45  
标签:web 国际化 系列 SpringMVC request springframework locale org import


在系列(7)中我们讲了数据的格式化显示,Spring在做格式化展示的时候已经做了国际化处理,那么如何将我们网站的其它内容(如菜单、标题等)做国际化处理呢?这就是本篇要将的内容—>国际化。

一.基于浏览器请求的国际化实现:

首先配置我们项目的springservlet-config.xml文件添加的内容如下:



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



在com.demo.web.controllers包中添加GlobalController.java内容如下:




package com.demo.web.controllers;

import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.support.RequestContext;
import com.demo.web.models.FormatModel;

@Controller
@RequestMapping(value = "/global")
public class GlobalController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})
    public String test(HttpServletRequest request,Model model){
        if(!model.containsAttribute("contentModel")){
            
            //从后台代码获取国际化信息
            RequestContext requestContext = new RequestContext(request);
            model.addAttribute("money", requestContext.getMessage("money"));
            model.addAttribute("date", requestContext.getMessage("date"));

            
            FormatModel formatModel=new FormatModel();

            formatModel.setMoney(12345.678);
            formatModel.setDate(new Date());
            
            model.addAttribute("contentModel", formatModel);
        }
        return "globaltest";
    }
    
}




这里展示模型还用系列(7)中的作为演示。

在项目中的源文件夹resources中添加messages.properties、messages_zh_CN.properties、messages_en_US.properties三个文件,其中messages.properties、messages_zh_CN.properties里面的"money", "date",为中文,messages_en_US.properties里面的为英文。

在views文件夹中添加globaltest.jsp视图,内容如下:




<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    下面展示的是后台获取的国际化信息:<br/>
    ${money}<br/>
    ${date}<br/>

    下面展示的是视图中直接绑定的国际化信息:<br/>
    <spring:message code="money"/>:<br/>
    <spring:eval expression="contentModel.money"></spring:eval><br/>
    <spring:message code="date"/>:<br/>
    <spring:eval expression="contentModel.date"></spring:eval><br/>
    
</body>
</html>




运行测试:

SpringMVC学习系列(8) 之 国际化_java

更改浏览器语言顺序,刷新页面:

SpringMVC学习系列(8) 之 国际化_java_02

 

二.基于Session的国际化实现:

在项目的springservlet-config.xml文件添加的内容如下(第一种时添加的内容要保留):



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

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />



更改globaltest.jsp视图为如下内容:




<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="test?langType=zh">中文</a> | <a href="test?langType=en">英文</a><br/>

    下面展示的是后台获取的国际化信息:<br/>
    ${money}<br/>
    ${date}<br/>

    下面展示的是视图中直接绑定的国际化信息:<br/>
    <spring:message code="money"/>:<br/>
    <spring:eval expression="contentModel.money"></spring:eval><br/>
    <spring:message code="date"/>:<br/>
    <spring:eval expression="contentModel.date"></spring:eval><br/>
    
</body>
</html>




更改GlobalController.java为如下内容:




package com.demo.web.controllers;

import java.util.Date;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;
import com.demo.web.models.FormatModel;

@Controller
@RequestMapping(value = "/global")
public class GlobalController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})
    public String test(HttpServletRequest request,Model model, @RequestParam(value="langType", defaultValue="zh") String langType){
        if(!model.containsAttribute("contentModel")){
            
            if(langType.equals("zh")){
                Locale locale = new Locale("zh", "CN"); 
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); 
            }
            else if(langType.equals("en")){
                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());
            
            //从后台代码获取国际化信息
            RequestContext requestContext = new RequestContext(request);
            model.addAttribute("money", requestContext.getMessage("money"));
            model.addAttribute("date", requestContext.getMessage("date"));

            
            FormatModel formatModel=new FormatModel();

            formatModel.setMoney(12345.678);
            formatModel.setDate(new Date());
            
            model.addAttribute("contentModel", formatModel);
        }
        return "globaltest";
    }
    
}




运行测试:

SpringMVC学习系列(8) 之 国际化_html_03

SpringMVC学习系列(8) 之 国际化_测试_04

 

三.基于Cookie的国际化实现:

把实现第二种方法时在项目的springservlet-config.xml文件中添加的



<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />



注释掉,并添加以下内容:



<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />



更改GlobalController.java为如下内容:




package com.demo.web.controllers;

import java.util.Date;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
//import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;

import com.demo.web.models.FormatModel;

@Controller
@RequestMapping(value = "/global")
public class GlobalController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})
    public String test(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"); 
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); 
            }
            else if(langType.equals("en")){
                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());*/
            
            if(langType.equals("zh")){
                Locale locale = new Locale("zh", "CN"); 
                //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
                (new CookieLocaleResolver()).setLocale (request, response, locale);
            }
            else if(langType.equals("en")){
                Locale locale = new Locale("en", "US"); 
                //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
                (new CookieLocaleResolver()).setLocale (request, response, locale);
            }
            else 
                //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale());
                (new CookieLocaleResolver()).setLocale (request, response, LocaleContextHolder.getLocale());
            
            //从后台代码获取国际化信息
            RequestContext requestContext = new RequestContext(request);
            model.addAttribute("money", requestContext.getMessage("money"));
            model.addAttribute("date", requestContext.getMessage("date"));

            
            FormatModel formatModel=new FormatModel();

            formatModel.setMoney(12345.678);
            formatModel.setDate(new Date());
            
            model.addAttribute("contentModel", formatModel);
        }
        return "globaltest";
    }
    
}




运行测试:

SpringMVC学习系列(8) 之 国际化_spring_05

SpringMVC学习系列(8) 之 国际化_java_06

关于<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />3个属性的说明(可以都不设置而用其默认值):




<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <!-- 设置cookieName名称,可以根据名称通过js来修改设置,也可以像上面演示的那样修改设置,默认的名称为 类名+LOCALE(即:org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE-->
    <property name="cookieName" value="lang"/>
    <!-- 设置最大有效时间,如果是-1,则不存储,浏览器关闭后即失效,默认为Integer.MAX_INT-->
    <property name="cookieMaxAge" value="100000">
    <!-- 设置cookie可见的地址,默认是“/”即对网站所有地址都是可见的,如果设为其它地址,则只有该地址或其后的地址才可见-->
    <property name="cookiePath" value="/">
</bean>




 

四.基于URL请求的国际化的实现:

首先添加一个类,内容如下:




import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;

public class MyAcceptHeaderLocaleResolver extends AcceptHeaderLocaleResolver {

    private Locale myLocal;

    public Locale resolveLocale(HttpServletRequest request) {
        return myLocal;
    } 

    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        myLocal = locale;
    }
  
}




然后把实现第二种方法时在项目的springservlet-config.xml文件中添加的



<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />



注释掉,并添加以下内容:



<bean id="localeResolver" class="xx.xxx.xxx.MyAcceptHeaderLocaleResolver"/>



“xx.xxx.xxx”是刚才添加的MyAcceptHeaderLocaleResolver 类所在的包名。

保存之后就可以在请求的URL后附上 locale=zh_CN 或 locale=en_US 如 http://xxxxxxxx?locale=zh_CN 来改变语言了,具体这里不再做演示了。

 

国际化部分的内容到此结束。

标签:web,国际化,系列,SpringMVC,request,springframework,locale,org,import
From: https://blog.51cto.com/u_16131764/6370149

相关文章

  • SpringMVC学习系列(6) 之 数据验证
    在系列(4)、(5)中我们展示了如何绑定数据,绑定完数据之后如何确保我们得到的数据的正确性?这就是我们本篇要说的内容—>数据验证。这里我们采用Hibernate-validator来进行验证,Hibernate-validator实现了JSR-303验证框架支持注解风格的验证。首先我们要到http://hibernate.org/validator......
  • SpringMVC学习系列(7) 之 格式化显示
    在系列(6)中我们介绍了如何验证提交的数据的正确性,当数据验证通过后就会被我们保存起来。保存的数据会用于以后的展示,这才是保存的价值。那么在展示的时候如何按照要求显示?(比如:小数保留一定的位数,日期按指定的格式等)。这就是本篇要说的内容—>格式化显示。从Spring3.X开始,Spring提供......
  • SpringMVC学习系列(10) 之 异常处理
    在项目中如何处理出现的异常,在每个可能出现异常的地方都写代码捕捉异常?这显然是不合理的,当项目越来越大是也是不可维护的。那么如何保证我们处理异常的代码精简且便于维护呢?这就是本篇要讲的内容—>异常处理。在SpringMVC中我们可以通过以下2中途径来对异常进行集中处理:一.继承Han......
  • Python工具箱系列(三十四)
    SQLAlchemy是著名的ORM(ObjectRelationalMapping-对象关系映射)框架。其主要作用是在编程中,把面向对象的概念跟数据库中表的概念对应起来。对许多语言(例如JAVA/PYTHON)来说就是定义一个对象,并且这个对象对应着一张数据库的表。而这个对象的实例,就对应着表中的一条记录。其整体思......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-1-环境准备与搭建
    1.简介有很多人私信留言宏哥问能不能介绍一下Playwright这款自动化神器的相关知识,现在网上的资料太少了。其实在各大博客和公众号也看到过其相关的介绍和讲解。要不就是不全面、不系统,要不就是系统全面但是人家是收费的。当然了宏哥接下来也可能介绍的不全面或者不系统,能力有限望......
  • Struct2系列漏洞POC整理
    Struct2-001%{#a=(newjava.lang.ProcessBuilder(newjava.lang.String[]{"pwd"})).redirectErrorStream(true).start(),#b=#a.getInputStream(),#c=newjava.io.InputStreamReader(#b),#d=newjava.io.BufferedReader(#c),#e=newchar[50000],#d.read(#e),#f=#co......
  • Spider理论系列--MongoDB(二)
    NoSQLMongodb下载mongodb的版本,两点注意根据业界规则,偶数为稳定版,如1.6.X,奇数为开发版,如1.7.X32bit的mongodb最大只能存放2G的数据,64bit就没有限制性能BSON格式的编码和解码都是非常快速的。它使用了C风格的数据表现形式,这样在各种语言中都可以高效地使用。NoSQL(NoSQL=NotOnly......
  • iOS MachineLearning 系列(20)—— 训练生成CoreML模型
    iOSMachineLearning系列(20)——训练生成CoreML模型本系列前面的文章详细的介绍了在iOS中与AI能力相关的API的使用,也介绍了如何使用训练好的CoreML模型来实现更强大的AI能力。然而,无论是成熟的API提供的能力,还是各种各样的三方模型,有时候都并不能满足某一领域内的定制化需求。当我......
  • 目标检测YOLOv1~v8系列
    目标检测YOLO系列YOLOv1blogs1:YOLOv1算法理解blogs2:<机器爱学习>YOLOv1深入理解YOLOv1总结:网络结构:激活函数:损失函数:输入和输出:input:448x448x3output:7x7x30output的30:Iou计算只在训练阶段,在测试阶段不进行IoU计算训练:训练中采用了dropo......
  • WPF入门教程系列二十六——DataGrid使用示例(3)
    WPF入门教程系列目录WPF入门教程系列二——Application介绍WPF入门教程系列三——Application介绍(续)WPF入门教程系列四——Dispatcher介绍WPF入门教程系列五——Window介绍WPF入门教程系列十一——依赖属性(一)WPF入门教程系列十五——WPF中的数据绑定(一) 五、DataGr......