zoukankan      html  css  js  c++  java
  • springMVC validator验证的使用

    http://blog.csdn.net/miketom155/article/details/45058195

     1. 实现Validator接口,对数据进行校验 

      

    @RequestMapping(value = "/pets/new", method = RequestMethod.POST)
    public String processCreationForm(Owner owner, @Valid Pet pet, BindingResult result, ModelMap model) {
    if (StringUtils.hasLength(pet.getName()) && pet.isNew() && owner.getPet(pet.getName(), true) != null){
    result.rejectValue("name", "duplicate", "already exists");
    }
    if (result.hasErrors()) {
    model.put("pet", pet);
    return VIEWS_PETS_CREATE_OR_UPDATE_FORM;
    } else {
    owner.addPet(pet);
    this.clinicService.savePet(pet);
    return "redirect:/owners/{ownerId}";
    }
    }

    @InitBinder("pet")
    public void initPetBinder(WebDataBinder dataBinder) {
    dataBinder.setValidator(new PetValidator());
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
    dataBinder.setDisallowedFields("id");
    }

    2. 通过注解方式对数据进行校验

    @Column(name = "address")
    @NotEmpty
    private String address;

    @RequestMapping(value = "/owners/{ownerId}/edit", method = RequestMethod.POST)
    public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, @PathVariable("ownerId") int ownerId) {
    if (result.hasErrors()) {
    return VIEWS_OWNER_CREATE_OR_UPDATE_FORM;
    } else {
    owner.setId(ownerId);
    this.clinicService.saveOwner(owner);
    return "redirect:/owners/{ownerId}";
    }
    }

  • 相关阅读:
    [SCOI2003]严格N元树
    CF280 C. Game on Tree
    [HDU2281]Square Number
    [HDU5391]Zball in Tina Town
    [HDU3988]Harry Potter and the Hide Story
    [HDU5794]A Simple Chess
    [HDU5451]Best Solver
    [HDU1724]Ellipse
    [HDU6304]Chiaki Sequence Revisited
    [HDU6343]Graph Theory Homework
  • 原文地址:https://www.cnblogs.com/newlangwen/p/6626950.html
Copyright © 2011-2022 走看看