类似于将参数放到properties配置文件中进行读取,我们也可以将各种message放到配置文件中
然后按照语言读取不同的配置响应到页面,从而实现国际化。
这里我们学习messageSource的使用。
一,添加配置文件spring-servlet-validator.xml
引入消息配置文件,这里只需要写明文件名中公共部分"message"即可
classpath:messages/message
二,在Spring-config.xml中引入以上配置:
并且配置localeResolver bean,管理locale
三,Spring-servlet.xml 中开启扫描校验:
四,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 getBean(String name, Class 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
更改语音环境为英文
再次测试:
可以看到返回的提示消息为英文。
使用freemarker也可以在页面上使用我们定义的message,不过这是另外一篇要讲述的了,有空再整理吧。