您的位置:首页 > 编程语言 > Java开发

【笔记】Spring MVC学习指南(七)验证器

2015-09-28 15:26 495 查看
第七章介绍的是校验器,看了一遍,感觉依然很简单。

继承接口,编写校验器实现类:

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


以上就是关于验证器这一环节的所有知识点,简单易用,忘了的话,速度扫一遍就会了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: