validate参数校验和数据回显

服务端校验

校验理解
项目中,通常使用较多的是前段的校验,比如在页面中js校验。对于安全要求较高的建议在服务端进行校验。

服务端校验:
控制层controller:校验页面请求的参数的合法性。在服务端控制层controller校验,不区分客户端类型(浏览器、手机客户端、远程调用);
业务层service(使用较多):主要校验关键业务参数,仅限于service接口中使用的参数
持久层dal:一般是不校验的

springMVC校验
springMVC使用hibernate的校验框架validation(与hibernate没什么关系)
校验思路:
页面提交请求的参数,请求到controller方法中,使用validate进行校验。如果校验出错,将错误信息展示到页面中。
准备:
hibernate校验框架validation所需要的jar包
hibernat-validator-4.3.0.Final.jar
jboss-loggin-3.1.0.CR2.jar
validation-api-1.0.0.GA.jar
配置校验器
<!-- 校验器 -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- hibernate校验器 -->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
<!-- 指定校验使用的资源文件,如果不指定默认使用classpath下的ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean>
<!-- 校验错误信息配置文件 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 资源文件名 -->
<property name="basenames">
<list>
<value>classpath:CustomValidationMessages</value>
</list>
</property>
<!-- 资源文件编码格式 -->
<property name="fileEncodings" value="utf-8" />
<!-- 对资源文件内容缓存时间,单位秒 -->
<property name="cacheSeconds" value="120" />
</bean>

校验器注入到处理器适配器
配置方式1:
<mvn:annotation-driver validator="vilidator"></mvc:annotation-driver>
配置方式2:
<bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator" />
</bean>
<!-- 注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingIntializer" ref="customBinder"></property>
</bean>
在pojo中定义校验规则:
public class Items {
private Integer id;
//校验名称在1到30字符中间
//mesage是提示校验出错显示的信息
@Size(min=1,max=30,message="请输入1~30个字符的商品名称")
private String name;

...
}
校验出错提示信息这样设置不太好,硬编码,我们在资源文件中配置,这里调用就好了
CustomValidationMessage.properties
#添加校验错误提示信息
items.name.length.error=请输入1~30个字符的商品名称
items.createtime.isNULL=请输入商品的生产日期
public class Items {
private Integer id;
//校验名称在1到30字符中间
//mesage是提示校验出错显示的信息
@Size(min=1,max=30,message="${items.name.length.error}")
private String name;

//非空校验
@NotNull(message="${items.createtime.isNULL}")
private Date createtime;

...
}
捕获错误校验信息:
//在需要验证的pojo前面添加@Validated,在需要验证的pojo后面添加,BindingResult bindingResult接受出错信息
//注意:@Validated和BindingResult对象时配对出现的,并且顺序是固定的(一前一后)
@RequestMapping("...")
public String editSubmit(HttpServletRequest request,Integer id,ItemsCustom itemsCustom,BindingResult bindingResult)throws Exception {

//获取验证错误信息
if(bindingResult.hasErrors()){
//输出错误信息
List<ObjectErros> allErrors = bindingResult.getAllErrors();
for(ObjectErrors objectErrors:allErrors){
//输出信息
System.out.println(objectError.getDefaultMessage());
}
}
...
}
在页面显示错误信息:
将allErrors放在model中就可以在jsp中得到了
model.addAttribute("allErrors",allErrors);

分组校验:
需求:
在pojo中定义校验规则,而pojo是被多个controller所共用,当不同的controller方法对同一个pojo进行校验,但是每一个controller都需要有不同的校验方式。
解决方法:
定义多个校验分组(其实是一个java接口),分组中定义有哪些规则
每个controller方法使用不同的校验分组
校验分组:
public interface ValidateGroup1{
//接口中不需要定义任何方法,但是对不同的校验规则进行分组
}
public interface ValidateGroup2{
//接口中不需要定义任何方法,但是对不同的校验规则进行分组
//次分组只校验商品的长度
}
在校验规则中添加分组:
public class Items {
private Integer id;
//校验名称在1到30字符中间
//mesage是提示校验出错显示的信息
//groups:次校验属于哪个分组,groups可以定义多个分组
@Size(min=1,max=30,message="${items.name.length.error}",groups={ValidateGroup1.class,ValidateGroup2.class})
private String name;

//非空校验
@NotNull(message="${items.createtime.isNULL}",groups={ValidateGroup2.class})
private Date createtime;

...
}
在controller方法使用指定分组的校验
//商品信息修改提交
//在需要校验的pojo前面加@Validated,在需要校验的pojo后面加BindingResult对象接收输出错误信息
//注意:@Validated和BindingResult对象是承兑出现,而且形参顺序是固定的(一前一后)
//value={ValidateGroup1.class}指定使用ValidateGroup1的校验
@RequestMapping("...")
public String editItemsSubmit(Model model,HttpServletRequest request,Integer id,@Validated(value={ValidateGroup1.class}) ItemsCustom itemsCustom,BindingResult bindingResult)throws Exception{
...
}

数据回显
1、什么是数据回显
提交后,如果出现错误,将刚才提交的数据会先到刚才的提交页面
2、数据回显的方法
pojo数据回显方法
1、springMVC默认对pojo进行回显
pojo数据传入controller方法后,springmvc自动将pojo放置到request域,key为类名的首字母小写
2、使用@ModelAttribute注解标识参数放在request中的key
@RequestMapping("...")
public String editItemsSubmit(Model model,HttpServletRequest request,Integer id,@ModelAttribute("items") @Validated(value={ValidateGroup1.class}) ItemsCustom itemsCustom,BindingResult result){
...
}
@ModelAttribute还有一个作用:在执行该Controller方法之前将方法返回值注入到request域
@ModelAttribute("itemtypes")
public Map<String,String> getItemTypes(){
...
}
页面上可以得到itemsTypes数据:
商品类型:
<select name="itemtype">
<c:forEach items="${itemtypes}" var="itemtype">
<option value="${itemtype.key}">${itemtype.value}</option>
</c:forEach>
</select>
3、使用model将提交的pojo回显到页面
model.addAttribute("items",itemsCustom);
简单数据类型回显
只能使用model的方式。

原文地址:https://www.cnblogs.com/aigeileshei/p/6274593.html