【笔记】Spring MVC学习指南(七)验证器
2015-09-28 15:26
495 查看
第七章介绍的是校验器,看了一遍,感觉依然很简单。
继承接口,编写校验器实现类:
除了这种写法,还可以通过在Controller类编写initBinder方法:
再或者利用@javax.validation.Valid注解:
以上是基于Spring自带的验证器,除此之外,还可以使用JSR 303 Validator范例,需要添加Hibernate Validator库。
实现方式有很大不同,是直接在model类中使用注解:
设置报错信息,在messages.properties中添加:
以上就是关于验证器这一环节的所有知识点,简单易用,忘了的话,速度扫一遍就会了。
继承接口,编写校验器实现类:
package app07a.validator; import app07a.domain.Product; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import java.util.Date; public class ProductValidator implements Validator { @Override public boolean supports(Class<?> klass) { return Product.class.isAssignableFrom(klass); // 当Product和klass为同一类型或者Product为klass的超类或接口时,返回true } @Override public void validate(Object target, Errors errors) { Product product = (Product) target; ValidationUtils.rejectIfEmpty(errors, "name", "productname.required"); ValidationUtils.rejectIfEmpty(errors, "price", "price.required"); ValidationUtils.rejectIfEmpty(errors, "productionDate", "productiondate.required"); Float price = product.getPrice(); if (price != null && price < 0) { errors.rejectValue("price", "price.negative"); } Date productionDate = product.getProductionDate(); if (productionDate != null) { // The hour,minute,second components of productionDate are 0 if (productionDate.after(new Date())) { System.out.println("production date is invalid"); errors.rejectValue("productionDate", "productiondate.invalid"); } } } }在需要执行验证操作的地方调用即可:
package app07a.controller; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import app07a.domain.Product; import app07a.validator.ProductValidator; @Controller public class ProductController { private static final Log logger = LogFactory .getLog(ProductController.class); @RequestMapping(value = "/product_input") public String inputProduct(Model model) { model.addAttribute("product", new Product()); return "ProductForm"; } @RequestMapping(value = "/product_save") public String saveProduct(@ModelAttribute Product product, BindingResult bindingResult, Model model) { logger.info("product_save"); System.out.println("prod save"); // 调用自定义的验证器,如果有错误,保存到bindingResult对象中 ProductValidator productValidator = new ProductValidator(); productValidator.validate(product, bindingResult); if (bindingResult.hasErrors()) { FieldError fieldError = bindingResult.getFieldError(); logger.info("Code:" + fieldError.getCode() + ", field:" + fieldError.getField()); return "ProductForm"; } // save product here model.addAttribute("product", product); return "ProductDetails"; } }
除了这种写法,还可以通过在Controller类编写initBinder方法:
@org.springframework.web.bind.annotation.InitBinder public void initBinder(WebDataBinder binder) { binder.setValidator(new ProductValidator()); binder.validate(); }
再或者利用@javax.validation.Valid注解:
public String saveProduct(@javax.validation.Valid @ModelAttribute Product product, BindingResult bindingResult, Model model)
以上是基于Spring自带的验证器,除此之外,还可以使用JSR 303 Validator范例,需要添加Hibernate Validator库。
实现方式有很大不同,是直接在model类中使用注解:
package app07b.domain; import java.io.Serializable; import java.util.Date; import javax.validation.constraints.Past; import javax.validation.constraints.Size; public class Product implements Serializable { private static final long serialVersionUID = 78L; @Size(min=1, max=10) private String name; private String description; private Float price; @Past private Date productionDate; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } public Date getProductionDate() { return productionDate; } public void setProductionDate(Date productionDate) { this.productionDate = productionDate; } }
设置报错信息,在messages.properties中添加:
Size.product.name = Product name must be 1 to 10 characters long Past.product.productionDate=Production date must a past date
以上就是关于验证器这一环节的所有知识点,简单易用,忘了的话,速度扫一遍就会了。
相关文章推荐
- Java基础知识强化之IO流笔记02:try...catch的方式处理异常
- List分类与用法总结
- Java垃圾回收finalize()作用详解
- FEDORA 20下STM32 ECLIPSE环境搭建
- Java的 CopyOnWriteArrayList
- Ubuntu eclipse alt+/不提示
- Eclipse设置默认文件的打开程序
- 2.Java安全之公钥与私钥-非对称加密
- Javabean
- 1、Java安全之秘密密钥-对称加密
- springMVC教程中级(四)Controller中级篇2(传图、json)
- Struts2五、Struts1与Struts2的区别
- Struts2五、Struts1与Struts2的区别
- Java动态代理的实现机制
- 卖火车票---java线程
- Java学习:内部类
- JAVA如何把一个float四舍五入到小数点后2位,以及多位
- 守护线程java thread setDaemon
- spring进阶四
- Struts2 四、Struts2 处理流程