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}";
    }
    }

  • 相关阅读:
    [Linux]
    [.Net]
    [.Net]
    [Linux]
    [Google]
    面向对象的7个基本设计原则
    windows SDK中的wininet写http客户端
    C++ 用libcurl库进行http通讯网络编程
    感悟
    关于Windows高DPI的一些简单总结
  • 原文地址:https://www.cnblogs.com/newlangwen/p/6626950.html
Copyright © 2011-2022 走看看