SpringMvc 国际化消息处理

类似于将参数放到properties配置文件中进行读取,我们也可以将各种message放到配置文件中

然后按照语言读取不同的配置响应到页面,从而实现国际化。

这里我们学习messageSource的使用。

一,添加配置文件spring-servlet-validator.xml

引入消息配置文件,这里只需要写明文件名中公共部分"message"即可

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<!-- 消息处理,可以直接使用properties的key值,返回的是对应的value值 -->
    <bean id="messageSource"
          class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
            	<value>classpath:messages/message</value>
            </list>
        </property>
        <!-- 必须设置成false,否则hibernate原有的校验信息无法返回value值-->
        <property name="useCodeAsDefaultMessage" value="false"/>
    </bean>

	<!-- 它在启动的时候会初始化hibernate validator,
	同时它引用的消息显示内容是前面定义的messageSource的消息内容文件 -->
    <bean id="myValidator"
          class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass"
                  value="org.hibernate.validator.HibernateValidator"/>
        <property name="validationMessageSource" ref="messageSource"/>
    </bean>

</beans>

二,在Spring-config.xml中引入以上配置:

<!-- Validator设置 -->
<import resource="classpath*:spring-servlet-validator.xml"/>

并且配置localeResolver bean,管理locale

<!-- 国际化消息处理 -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
	<property name="defaultLocale" value="zh_CN" />
</bean>

三,Spring-servlet.xml 中开启扫描校验:

	<mvc:annotation-driven validator="myValidator">
四,message配置文件,这里我们准备两个,一个中文,一个英文。放在Classpath下面。

message_zh_CN.properties

#============================= message ===============================
msg.success=\u8BBF\u95EE\u6210\u529F
valid.userInfo.userName=\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A
valid.userInfo.email=\u90AE\u7BB1\u4E0D\u80FD\u4E3A\u7A7A
valid.userInfo.phone=\u7535\u8BDD\u53F7\u7801\u4E0D\u80FD\u4E3A\u5C0F\u6570
valid.userInfo.userName.notRepeat=\u7528\u6237\u540D\u5DF2\u5B58\u5728
valid.userInfo.userName.notLogin=\u7528\u6237\u540D\u5BC6\u7801\u4E0D\u6B63\u786E
message_en_US.properties
#============================= message ===============================
msg.success=success
valid.userInfo.userName=userName can not be null
valid.userInfo.email=email can not be null
valid.userInfo.phone=param phone is error
valid.userInfo.userName.notRepeat=userName already exsist
valid.userInfo.userName.notLogin=user not login

五,准备工具类,用于获取消息配置的内容

SpringUtils 这里主要是要实现ApplicationContextAware,使用applicationContext.getMessage方法获取。

package com.maven.web.util;

import java.util.Locale;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.servlet.LocaleResolver;

/**
 * Utils - Spring
 * 
 */
@Component("springUtils")
@Lazy(false)
public final class SpringUtils implements ApplicationContextAware, DisposableBean {

	/** applicationContext */
	private static ApplicationContext applicationContext;
	
	/** localeResolver */
	private static LocaleResolver localeResolver;

	/**
	 * 不可实例化
	 */
	private SpringUtils() {
	}

	public void setApplicationContext(ApplicationContext applicationContext) {
		SpringUtils.applicationContext = applicationContext;
	}

	public void destroy() throws Exception {
		applicationContext = null;
	}

	/**
	 * @return applicationContext
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * @param name Bean名称
	 * @return 实例
	 */
	public static Object getBean(String name) {
		Assert.hasText(name);
		return applicationContext.getBean(name);
	}

	/**
	 * @param name Bean名称
	 * @param type Bean类型
	 * @return 实例
	 */
	public static <T> T getBean(String name, Class<T> type) {
		Assert.hasText(name);
		Assert.notNull(type);
		return applicationContext.getBean(name, type);
	}

	/**
	 * @param code 代码
	 * @return 国际化消息
	 */
	public static String getMessage(String code) {
		Locale locale = getLocaleResolver().resolveLocale(null);
		return applicationContext.getMessage(code, null, locale);
	}
	
	/**
	 * @param code 代码
	 * @param args 参数
	 * @return 国际化消息
	 */
	public static String getMessage(String code, Object[] args) {
		Locale locale = getLocaleResolver().resolveLocale(null);
		return applicationContext.getMessage(code, args, locale);
	}
	
	/**
	 * @return localeResolver
	 */
	private static LocaleResolver getLocaleResolver() {
		if (localeResolver == null) {
			localeResolver = getBean("localeResolver", LocaleResolver.class);
		}
		return localeResolver;
	}

}
准备工作做好了,我们对上一篇的校验规则进行改造。

首先是UserInfoRequest,我们在注解后面加上自定义的message

package com.maven.web.entity;

import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;

import com.maven.web.validator.NotRepeat;

/**
 * 接收前端传递数据的映射类
 * @author Administrator
 *
 */
public class UserInfoRequest {
	
	@NotNull(message="{valid.userInfo.userName}")
	@NotRepeat
	private String userName;

	@Size(min=6, max=8)
    private String password;

	@Email
    private String email;

    /**
     * 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度
     */
    @Digits(integer=11,fraction=0,message="{valid.userInfo.phone}")
    private String phone;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	@Override
	public String toString() {
		return "UserInfoRequest [userName=" + userName + ", password=" + password + ", email=" + email + ", phone="
				+ phone + "]";
	}
    
    

}

自定义注解@NotRepeat也使用国际化消息替代原来定义的中文消息

package com.maven.web.validator;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target( { METHOD, FIELD, ANNOTATION_TYPE })  
@Retention(RUNTIME)  
@Constraint(validatedBy = UserNameValidator.class)  
@Documented 
public @interface NotRepeat {
	
	String message() default "{valid.userInfo.userName.notRepeat}";
	
	Class<?>[] groups() default {};  
    
    public abstract Class<? extends Payload>[] payload() default {}; 

}
在controller中我们也使用上面定义的SpringUtil获取国际化消息。
	/**
	 * 校验ajax传递的json字符串
	 * @param userInfo
	 * @return
	 */
	@RequestMapping(value="/ajax/post",method=RequestMethod.POST)
	public Result validAjax(@RequestBody @Valid UserInfoRequest userInfo){
		logger.info("如果校验通过则打印参数:"+userInfo);
		Result r = new Result(ErrorCode.SUCCESS);
		r.setDetailMsg(SpringUtils.getMessage("msg.success"));
		return r;
	}
接下来访问测试, http://localhost:8088/com.maven.web/valid/ajax/post


更改语音环境为英文

	<!-- 国际化消息处理 -->
	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
<!-- 		<property name="defaultLocale" value="zh_CN" /> -->
		<property name="defaultLocale" value="en_US" />
	</bean>

再次测试:



可以看到返回的提示消息为英文。

使用freemarker也可以在页面上使用我们定义的message,不过这是另外一篇要讲述的了,有空再整理吧。




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值