9月22日Spring笔记
发布时间:
本文字数:407 字 阅读完需:约 2 分钟
数据转换和校验
SpringMVC通过反射机制对目标处理方法进行解析,将请求消息绑定到处理方法的参数中。
自定义消息转换器
spring-mvc.xml
<!-- 开启RequestMapping映射处理器和适配器-->
<mvc:annotation-driven conversion-service="conversionServiceFactory">
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=utf-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".html"></property>
</bean>
<bean id="conversionServiceFactory" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.zr.converter.UserConverter"></bean>
</set>
</property>
</bean>
UserConverter.java
package com.zr.converter;
import com.zr.vo.User;
import org.springframework.core.convert.converter.Converter;
public class UserConverter implements Converter<String, User> {
@Override
public User convert(String source) {
User user = new User();
String[] data = source.split("-");
user.setUserId(data[0]);
user.setUserName(data[1]);
return user;
}
}
UserController.java
@RequestMapping("/converter.action")
public void converter(@RequestParam("data") User user){
System.out.println(user);
}
效果:传入key为data的属性,其值将被转换为User类,转换规则见UserConverter.java
数据的后台校验
JSR 303是Java为Bean数据合法性校验提供的标准框架,它已经包含在 JavaEE6.0中;
JSR 303通过在 Bean 属性上标注类似于@NotNull、@Max等标准的注解指定校验规则,并通过标准的验证接口对 Bean进行验证;
校验示例
导入hibernate jar包,在对象类上加相应的注解,在controller层使用@Validated
注解
pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.0.Final</version>
</dependency>
User.java
public class User {
@NotEmpty(message = "用户账号不能为空")
private String userId;
private String userName;
@NotEmpty(message = "密码不能为空")
private String password;
}
UserController.java
@ResponseBody
@PostMapping(value = "login.action", consumes = {"application/x-www-form-urlencoded"})
// @Validated 注解,必须和Errors配合使用
public String login(@Validated User user, Errors errors){
if(errors.hasFieldErrors()){
return JSON.toJSONString(AjaxResult.fail(200,errors.getFieldError().getDefaultMessage(), null));
}
User u = new User();
u.setUserId(user.getUserId());
u.setPassword(Md5Util.md5(user.getPassword()));
AjaxResult robj = userService.login(u);
return JSON.toJSONString(robj);
}
国际化
message.properties
默认
message_zh_CN
中文中国
biz.query.success=默认:查询成功{0}
0为占位符
UserController.java
@Autowired
private ResourceBundleMessageSource messageSource;
@ResponseBody
@PostMapping("/getUserList.action")
public String getUserList(Locale locale){
AjaxResult robj = userService.getList();
if(robj.isSuccess()){
robj.setMessage(messageSource.getMessage("biz.query.success",new Object[]{"!"}, locale));
// {"!"}替换properties文件中的占位符{0}
}
String str = JSON.toJSONString(robj);
return str;
}
spring-mvc.xml
<!-- 国际化-->
<bean class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="message"></property>
<property name="useCodeAsDefaultMessage" value="true"></property>
</bean>
Powerd by YlBlog(玉龙博客)