如何实现 Spring MVC i18n 国际化,动态设置默认语言

如何实现 Spring MVC i18n 国际化,动态设置默认语言,第1张

1.在spring配置文件中配置资源文件properties的位置及公共名,下列配置指定的properties文件处于src目录下的resources文件夹中,名字为message_info_*.properties。

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">

<propertyname="basenames">

<list>

<value>resources/message_info</value>

</list>

</property>

<propertyname="useCodeAsDefaultMessage"value="true"/><!--

Set whether to usethe message code as default message instead of

throwing aNoSuchMessageException. Useful for development

anddebugging. -->

</bean>

2.在spring配置文件中配置基于session的处理,将提交上来的locale参数进行处理,下列代码默认加载的语言是中文简体。

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

<propertyname="defaultLocale"value="zh_CN"></property>

</bean>

3.在spring配置文件中的controller内配置相应的拦截器。

<beanid="className"

class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">

<propertyname="interceptors">

<list>

<beanclass="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>

</list>

</property>

</bean>

4.相应的properties文件内写入对应的语言,配置文件的语言信息以keyvalue的形式进行存储。

5.利用jstl的fmt标签库进行相应数据的国际化。

1)导入相应的fmt标签库<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

2)需要国际化处写入<fmt:messagekey="title"></fmt:message>标签,此处将显示相应properties文件中名为title的信息。

3)页面上写成三个连接用于控制国际化的转换

<ahref="/CloudPortal/staff/goindex.do?locale=zh_CN">Chinese</a>//message_info_zh_CN.properties

<ahref="/CloudPortal/staff/goindex.do?locale=en_US">English</a>//message_info_en_US.properties

<ahref="/CloudPortal/staff/goindex.do?locale=zh_TW">Chinese(TW)</a>//message_info_zh_TW.properties

locale内部固定的参数用于判断读取请求的配置文件。

-------------------------------------------------------------

分割线--------------2014-11-11 by

zhang------------------------------------------------------------------------------------------------------

springmvc如何实现国际化

1.springmvc实现国际化有多种方式(自行百度)。

几种方式无非就是配置国际化方式和读取国际化资源文件从而实现国际化,下面本文介绍基于session的国际化配置,感觉配置比较方便快捷一些。

(1).首先配置配置国际化在spring-servlet.xml,即springmvc的配置文件中(xxx-servlet.xml)。

<!-- springmvc 国际化配置 (基于Session的国际化配置 方式)-->

<bean id="localeResolver"

class="org.springframework.web.servlet.i18n.SessionLocaleResolver">

</bean>

<bean id="messageSource"

class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

<property name="fallbackToSystemLocale">

<value>false</value>

</property>

<property name="basename" value="/WEB-INF/i18n/resources/messages" />

</bean>

(2)在WEB-INF文件夹下按照

[html] view plaincopy

/WEB-INF/i18n/resources/messages

配置新建文件夹,在文件夹里面新建配置文件

messages_zh_CN.properties(中文国际化资源文件),messages.properties(英文国际化资源文件)国际化资源文件。

到此配置完毕。

注:springmvc的国际化必须要经过控制器Controller才能生效。

2.如何在jsp页面读取国际化

(1)引入<spring:message/>标签如:<spring:message key=''user.manage.role/>

或者

(2)引入<fmt:message/>标签例如<fmt:message key='user.manage.role'/>,其中user.manage,role在messages_zh_CN.properties中配置为:user.manage.role=\u89D2\u8272,在messages.properties中配置为user.manage.role=Role,即可。

一、基于浏览器语言的国际化配置 使用Spring的MVC,并且配置中有配置Resource文件 Xml代码 以下是引用片段: 其中,message-info是你的properties文件的通用名。如:我的配置文件叫 message-info.properties,message-info_zh_CN.properties等等,只要有了这个配置,然后配置JSP 渲染器为JSTL支持的,那么在你的JSP文件中使用fmt标记就可以实现客户浏览器语言国际化了。 如: 以下是引用片段: 其中的info.login.title和你的资源文件对应. 另外一种方式是使用spring自带的标签显示国际化信息,如: 以下是引用片段:

"/>

二、基于动态加载的国际化配置 1、基于请求的国际化配置 基于请求的国际化配置是指,在当前请求内,国际化配置生效,否则自动以浏览器为主。 配置方式如下: 首先配置拦截器 以下是引用片段: 这个配置呢,是不论请求级别的国际化,还是Cookie级别的国际化,再或者Session级别的国际化,都必需有配置这个拦截器,否则会不能使用。 配好上面的拦截器之后,就将拦截器注入到你的UrlHandlerMapping中,例如: Xml代码 以下是引用片段: 1 这个时候,但凡有了符合UrlMapping的请求,就会被拦截,并且开始配置国际化参数 以下是引用片段: 默认的参数名为locale主意大小写。里面放的就是你的提交参数。如:en_US,zh_CN之类的,这个时候,你在页面上加一句简体中文 如果你的资源中,饱含建议中文的配置,那么就会变成你确定的简体中文拉。 2、基于Session的国际化配置 拦截器和基于请求的相同 Session的配置如下: 以下是引用片段: 在你的处理的Controller中,将提交上来的locale字段信息生成真正的Locale对象,然后将对象保存在Session中,默认保存的ID是SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME 这样,当你的Session不过期,那么语言种类始终保持正确的说。我一直是这样子用的,我觉得还是Session的好,老外们用了很满意。 3、基于Cookie的国际化配置 这个我就不说了,反正用的不多,至少我做的项目能不用Cookie就不用Cookie,所以,基于Cookie的国际化配置我就不细说了,如果想知道怎么配置,那么下载一个Spring,其中的例子程序就是用Cookie配置的,你自己读代码就OK了。 三、注意事项 如果不用默认的浏览器语言国际化方式,那么拦截器一定要配置,如果你有多个UrlMapping,那么就每个都配上拦截器。 至于配置的LocaleResolver的名字,一定要用上面的配置中的名字localeResolver当然了,这个是默认的名字来的,自己设置成别的也可以,但是就是麻烦,反正我用默认的就感觉不错 解决问题: 在前几天引用“Spring的MVC I18N-国际化相关配置 ”并做了测试,发现 有一问题。程序运行会抛出异常 “Cannot change HTTP accept header - use a different locale resolution strategy”,根本原因是spring source 做了限制,源码如下 Java代码 以下是引用片段: public class AcceptHeaderLocaleResolver implements LocaleResolver { public Locale resolveLocale(HttpServletRequest request) { return request.getLocale()} public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { throw new UnsupportedOperationException( "Cannot change HTTP accept header - use a different locale resolution strategy")} } 请注意上面的类,该类允许继承,所以需要改写setLocale方法,源码示范如下 Java代码 以下是引用片段: package org.springframework.web.servlet.i18nimport java.util.Localeimport javax.servlet.http.HttpServletRequestimport javax.servlet.http.HttpServletResponseimport org.springframework.web.servlet.DispatcherServletimport org.springframework.web.servlet.LocaleResolverpublic class MyAcceptHeaderLocaleResolver extends AcceptHeaderLocaleResolver { private Locale myLocalpublic Locale resolveLocale(HttpServletRequest request) { return myLocal} public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { myLocal = locale} } 然后在action-servlet.xml里的设置为 Xml代码 以下是引用片段: chinese.do=filenameController us.do=filenameController

spring mvc+myBatis配置详解

一、spring mvc

Spring框架(框架即:编程注解+xml配置的方式)MVC是Spring框架的一大特征,Spring框架有三大特征(IOC(依赖注入),AOP(面向切面),MVC(建模M-视图V-控制器C)。框架一般用于团队开发,使用分层的方式使每个人完成不同的模块,然后再组合在一起,使完成项目。

以下是Spring mvc具有的能加速开发的功能列表:

Spring mvc中提供了一个DispatchServlet,无需额外开发Spring mvc中使用基于xml的配置文件,可以编辑,而无需重新编译应用程序Spring mvc实例化控制器,并根据用户输入来构造Bean。

Spring mvc可以自动绑定用户输入,并正确的转换数据类型。例如,Spring mvc能自动解析字符串,并设置float或decimal类型的属性.

Spring mvc可以校验用户输入,若校验不通过,则重定向回输入表单。输入校验是可选的,支持编程方式以及声明。关于这一点,Spring mvc内置了常见的校验器Spring mvc是Spring框架的一部分,可以利用Spring提供的其他能力。

Spring mvc支持国际化和本地化。支持根据用户区域显示多国语言Spring mvc支持多种视图技术。最常见的JSP技术以及其他技术包括Velocity和FreeMarker.

配置spring mvc

1、导入Spring需要的jar 包

2、配置spring-mvc.xml

复制代码

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="springframework/schema/beans"xmlns:xsi="w3/2001/XMLSchema-instance"xmlns:context="springframework/schema/context"xmlns:jdbc="springframework/schema/jdbc"xmlns:jee="springframework/schema/jee"xmlns:tx="springframework/schema/tx"xmlns:aop="springframework/schema/aop"xmlns:mvc="springframework/schema/mvc"xmlns:util="springframework/schema/util"xmlns:jpa="springframework/schema/data/jpa"xsi:schemaLocation="springframework/schema/beans springframework/schema/beans/spring-beans-3.2.xswww.66298899.comrk/schema/context springframework/schema/context/spring-context-3.2.xswww.66298899.comrk/schema/jdbc springframework/schema/jdbc/spring-jdbc-3.2.xswww.66298899.comrk/schema/jee springframework/schema/jee/spring-jee-3.2.xswww.66298899.comrk/schema/tx springframework/schema/tx/spring-tx-3.2.xswww.66298899.comrk/schema/data/jpa springframework/schema/data/jpa/spring-jpa-1.3.xswww.66298899.comrk/schema/aop springframework/schema/aop/spring-aop-3.2.xswww.66298899.comrk/schema/mvc springframework/schema/mvc/spring-mvc-3.2.xswww.66298899.comrk/schema/util springframework/schema/util/spring-util-3.2.xsd">

<!-- HandlerMapping -->

<mvc:annotation-driven/>

开启spring mvc注解扫描,如果不基于注解: 该类需要继承 CommandController 或者 其他很多 参见 spring帮助.我用的是基于注解的,这样比较方便<!-- 扫描Controller,Service -->

<context:component-scan

base-package="com.包名"/>

开启组件扫描,请确保所有的控制器都在基本包下,并且不要制定一个太宽泛的基本包</beans>

复制代码

补充:

第一个为开启spring mvc注解扫描,如果不基于注解: 该类需要继承 CommandController 或者 其他很多 参见 spring帮助.我用的是基于注解的,这样比较方便第二个为开启组件扫描Spring使用扫描机制来找到应用程序中所有基于注解的控制器类,为了能保证Spring你那个找到你的控制器,a.需要在Spring mvc中配置spring-contextb.在<context:component-scan base-package="com.包名"/>元素中指定控制器类的基本包基于此,在Controller中可以方便调用了,实例见最下方3.部署web.xmlDispatcherServlet作为Spring mvc框架中的一级控制器(前端控制器),是浏览器发送请求的入口该Servlet的全称是org.springframework.web.servlet.DispatcherServlet.

要使用这个Servlet,需要把他配置在部署描述符(web.xml),应用servlet和servlet-mapping元素如下:

相关解释:

1、servlet元素内的on-startup元素是可选的。if存在,表示它将在应用程序启动时就装在servlet并调用它的init方法。else,则在该servlet的第一个请求是加载。

2、Dispatcher Servlet将会使用spring mvc诸多默认组件。此外,初始化时,它会寻找一个在应用程序下的web-INF目录下 的配置文件,该配置文件的命名规则如下servletName-servlet.xml其中servletName是在部署描述符中的Dispatcher Servlet的名字。如图所示,本例中的servlet-name为springmvc,则在初始化的时候会找到第二步配置的springmvc.xml文件.

3、当然springmvc.xml文件也可以放到应用程序目录中的任何地方,<init-param></init-param>元素就是为了实现这个功能的。

其中的<param-name>不用改,而<param-value>则包含配置文件的路劲。

补充一下:(1)Spring可以通过指定classpath*:与classpath:前缀加路径的方式从classpath加载文件,如bean的定义文件.

classpath*:的出现是为了从多个jar文件中加载相同的文件.

classpath:只能加载找到的第一个文件

(2) url-pattern的写法

1 三种写法

① 完全匹配

<url-pattern>/test/list.do</url-pattern>

② 目录匹配

<url-pattern>/test/*</url-pattern>

③ 扩展名匹配

<url-pattern>*.do</url-pattern>

2 注意事项

容器会首先查找完全匹配,如果找不到,再查找目录匹配,如果也找不到,就查找扩展名匹配。

如果一个请求匹配多个“目录匹配”,容器会选择最长的匹配。

定义”/*.action”这样一个看起来很正常的匹配会报错?因为这个匹配即属于路径映射,也属于扩展映射,导致容器无法判断。

“/” 是用来定义default servlet映射的。

*.do它不是一个文件,并没有一个真正的.do文件存在,只是一个servlet映射.意思是URL里一切以.do结尾的URL都驱动servlet里设置的那个类而*则是所有请求都交由servlet里设置的那个类处理!

二、MyBatis的配置和使用

Spring与MyBatis结合,主要是由Spring管理数据库访问组件Dao,数据库访问组件主要是基于MyBatis实现,在Spring环境中使用MyBatis实现数据库访问组件过程是:首先需要引入一个Spring和MyBatis整合的开发包 mybatis-spring-1.2.2.jar。在Spring配置中定义SqlSessionFactoryBean,等价于SqlSessionFactory放入Spring容器管理。(不需要开发者利用手工创建SqlSessionFactory对象,需要开发者定义式注入连接信息和SQL定义的XML信息)在Spring配置中定义MapperFactoryBean,可以根据指定的Mapper接口生成一个Mapper实现类接口。需引入引入开发包:spring ioc,spring aop,dbcp,mybatis,驱动,mybatis-spring.jar。添加Spring框架的配置文件主要有applicationContext.xml,根据user表编写实体类User,编写UserMapper.xml(定义SQL语句),并且编写UserMapper接口(与UserMapper.xml映射),在applicationContext.xml中配置组件SqlSessionFactoryBean,Mapper FactoryBean。最后测试MapperFactoryBean生成的UserMapperDao实例。

MyBatis的两个特点:

1.MyBatis采用SQL与Entity映射,对JDBC封装程度较轻2.MyBatis自己写SQL,更具有灵活性配置MyBatis

(1)导入jar包

(2)创建数据库

(3)添加MyBatis.xml配置文件

复制代码

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="springframework/schema/beans"xmlns:xsi="w3/2001/XMLSchema-instance"xmlns:context="springframework/schema/context"xmlns:jdbc="springframework/schema/jdbc"xmlns:jee="springframework/schema/jee"xmlns:tx="springframework/schema/tx"xmlns:aop="springframework/schema/aop"xmlns:mvc="springframework/schema/mvc"xmlns:util="springframework/schema/util"xmlns:jpa="springframework/schema/data/jpa"xsi:schemaLocation="springframework/schema/beans springframework/schema/beans/spring-beans-3.2.xswww.66298899.comrk/schema/context springframework/schema/context/spring-context-3.2.xswww.66298899.comrk/schema/jdbc springframework/schema/jdbc/spring-jdbc-3.2.xswww.66298899.comrk/schema/jee springframework/schema/jee/spring-jee-3.2.xswww.66298899.comrk/schema/tx springframework/schema/tx/spring-tx-3.2.xswww.66298899.comrk/schema/data/jpa springframework/schema/data/jpa/spring-jpa-1.3.xswww.66298899.comrk/schema/aop springframework/schema/aop/spring-aop-3.2.xswww.66298899.comrk/schema/mvc springframework/schema/mvc/spring-mvc-3.2.xswww.66298899.comrk/schema/util springframework/schema/util/spring-util-3.2.xsd">

<bean id="dbcp"

class="org.apachemons.dbcp.BasicDataSource">

<property name="username" value="****">

</property>

<property name="password" value="***">

</property>

<property name="driverClassName"

value="com.mysql.jdbc.Driver">

</property>

<property name="url"

value="jdbc:mysql:///cloud_note">

</property>

<!-- <property name="url" value="jdbc:mysql://localhost:3306/cloud_note?useUnicode=true&characterEncoding=utf-8"></property>-->

</bean>

<bean id="ssf"

class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dbcp">

</property>

<property name="mapperLocations"

value="classpath:com/niuniu/sql/*.xml">

</property>

</bean>

<bean id="mapperscanner"

class="org.mybatis.spring.mapper.MapperScannerConfigurer">

<property name="sqlSessionFactory" ref="ssf">

</property>

<property name="basePackage"

value="com.niuniu.dao">

</property>

</bean>

</beans>

复制代码

(4)定义表所对应的实体类,如下图所示

代码如下:

复制代码

package com.niuniu.entity

import java.io.Serializable

public class User implements Serializable {private String cn_user_idprivate String cn_user_name

private String cn_user_password

private String cn_user_token

private String cn_user_nick

public String getCn_user_id() {

return cn_user_id

}

public void setCn_user_id(String cnUserId) {cn_user_id = cnUserId}

public String getCn_user_name() {

return cn_user_name

}

public void setCn_user_name(String cnUserName) {cn_user_name = cnUserName}

public String getCn_user_password() {

return cn_user_password

}

public void setCn_user_password(String cnUserPassword) {cn_user_password = cnUserPassword}

public String getCn_user_token() {

return cn_user_token

}

public void setCn_user_token(String cnUserToken) {cn_user_token = cnUserToken}

public String getCn_user_nick() {

return cn_user_nick

}

public void setCn_user_nick(String cnUserNick) {cn_user_nick = cnUserNick}

}

复制代码

(5)定义 *** 作users表的sql映射文件UserMapping.xml复制代码<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//ibatis.apache//DTD Mapper 3.0//EN""http://ibatis.apache/dtd/ibatis-3-mapper.dtd">

<mapper namespace="com.niuniu.dao.UserDao">

<insert id="save" parameterType="com.niuniu.entity.User">

insert into cn_user(

cn_user_id,cn_user_name,

cn_user_password,cn_user_token,

cn_user_nick)

values(#{cn_user_id},#{cn_user_name},#{cn_user_password},#{cn_user_token},#{cn_user_nick})</insert>

<select id="findByName" parameterType="string"resultType="com.niuniu.entity.User">

select * from cn_user

where cn_user_name=#{name}

</select>

</mapper>

复制代码

(6)写Controller,进行测试。

复制代码

@Controller//将类名前加上该注解,当spring启动或者web服务启动 spring会自动扫描所有包(当然,这个可以设置,见上述Springmvc的配置)作用: 就是告诉服务器这个类是MVC中的C, 这个类可以接收用户请求、处理用户请求@RequestMapping("/note")//这个控制类里面可以有很多方法,哪个方法用来处理用户请求,就在那个方法前面 加 @RequestMapping(“/xxxxx请求路径”)public class LoadNoteDetailController {@Resource//直接使用@Resource注解一个域(field)同样是可能的。通过不暴露setter方法,代码愈发紧凑并且还提供了域不可修改的额外益处。

//正如下面将要证明的,@Resource注解甚至不需要一个显式的字符串值,在没有提供任何值的情况下,域名将被当作默认值。

//该方式被应用到setter方法的时候,默认名是从相应的属性衍生出来,换句话说,命名为'setDataSource'的方法被用来处理名为'dataSource'的属性。

private NoteService noteService

@RequestMapping("/loaddetail.do")//映射到JSP的前台页面中ajax发布的请求,打开相应的页面↑@ResponseBody ↑public NoteResult execute(String noteId){ ↑NoteResult result=noteService.loadDetail(noteId) ↑return result//当请求处理完毕后,返回值决定了该处理完毕后,用户将跳转到那个页面.这个很重要。service调util}

}

复制代码

知识补充:

@Resource

@Resource默认按照ByName自动注入,有两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性 则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既 不制定name也不制定type属性,这时将通过反射机制使用byName自动注入策略。

@ResponseBody

作用:

该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:

返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/6658053.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-26
下一篇 2023-03-26

发表评论

登录后才能评论

评论列表(0条)

保存