如果我们有两个模型对象数据,则验证表单

时间:2017-12-14 05:22:51

标签: spring-mvc

通常我在spring mvc中看到过这样的服务器端验证,例如有一个客户页面,其中包含客户相关信息,如customerName,customerAddress,customerPhoneNumber,我们将要 客户模型对象然后在弹簧控制器中我们打算像这样调用

Spring Controller

@RequestMapping(value = "/customerRegistrationScreen")
    public String customerRegistrationScreen(Model model) {
        Customer customer= new Customer();
        model.addAttribute("customer", customer);       
        return "customerRegistrationScreen";
    }


@RequestMapping(value = "/doCustomerRegistration", method = RequestMethod.POST)
 public ModelAndView registerCustomer(@ModelAttribute("customer") @Validated Customer customer, BindingResult result,Model model) {
        if (result.hasErrors()) {

        } else {

        }
    }

CustomerValidator类

@Component
public class CustomerValidator implements Validator {

   @Override
   public boolean supports(Class<?> clazz) {
      return Customer.class.equals(clazz);
   }

   @Override
   public void validate(Object obj, Errors err) {

      ValidationUtils.rejectIfEmpty(err, "name", "customer.name.empty");
      ValidationUtils.rejectIfEmpty(err, "email", "customer.email.empty");
      ValidationUtils.rejectIfEmpty(err, "gender", "customer.gender.empty");
      ValidationUtils.rejectIfEmpty(err, "languages", "customer.languages.empty");

      User user = (User) obj;

      Pattern pattern = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$",
            Pattern.CASE_INSENSITIVE);
      if (!(pattern.matcher(customer.getEmail()).matches())) {
         err.rejectValue("email", "user.email.invalid");
      }

   }

}

customerRegistration.jsp

<form:form  method="post" modelAttribute="customer" action="doCustomerRegistration">

</form:form>

如果jsp有两个模型对象信息,如Customer和产品信息,如customerName,customerAddress,customerPhoneNumber,productID,productName,productPrice,我喜欢这里有两个模型对象,如客户 &安培;产品如果我有两个模型对象如何从jsp和Spring控制器映射模型属性以及如何为验证进行服务器端验证

1 个答案:

答案 0 :(得分:3)

尽管在每种形式中保持模型分离是个好主意,但对于这个特定用例,可以通过以下步骤来实现。

实现此目的的最佳方法是将Model属性包装在一个包装类中,并在验证中使用它。

  1. 让我们说产品类看起来像这样。

    公共类产品{

    String productName;    //其他字段及其getter setter }

  2. 创建一个包装类CustomerProduct

    的包装类

    公共类CustomerProductWrapper {

    private Customer customer;
    
    private Product product;
    
    //getter setter
    

    }

  3. 在验证程序类中,更改supports()方法的实现,如下所示

    @覆盖    public boolean supports(Class clazz){       return CustomerProductWrapper .class.equals(clazz);    }

  4. 2.1将验证方法的实施改为如下

    @Override
       public void validate(Object obj, Errors err) {
    

    //您现在获得的对象是CustomerProductWrapper对象 //使用此对象引用字段

          ValidationUtils.rejectIfEmpty(err, "customer.name", "customer.name.empty");
          ValidationUtils.rejectIfEmpty(err, "customer.email", "customer.email.empty");
          ValidationUtils.rejectIfEmpty(err, "customer.gender", "customer.gender.empty");
          ValidationUtils.rejectIfEmpty(err, "customer.languages", "customer.languages.empty");
    
          CustomerProductWrapper cpw= (CustomerProductWrapper ) obj;
    
          Pattern pattern = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$",
                Pattern.CASE_INSENSITIVE);
          if (!(pattern.matcher(cpw.getCustomer().getEmail()).matches())) {
             err.rejectValue("customer.email", "user.email.invalid");
          }
    
    //validate a Product field
    
     ValidationUtils.rejectIfEmpty(err, "product.productName", "product.name.empty");
    
       }
    
    1. 在控制器映射中,

      public String customerRegistrationScreen(Model model){         CustomerProductWrapper cpw = new CustomerProductWrapper();         model.addAttribute(“cpw”,cpw);
              返回“customerRegistrationScreen”;     }

    2. 并且

      @RequestMapping(value = "/doCustomerRegistration", method = RequestMethod.POST)
       public ModelAndView registerCustomer(@ModelAttribute("cpw") @Validated CustomerProductWrapper  cpw, BindingResult result,Model model) {
              if (result.hasErrors()) {
      
              } else {
      
              }
          }
      

      最后在你的视图页面

      <form:form  method="post" modelAttribute="cpw" action="doCustomerRegistration">
      
      </form:form>
      

      还可以使用cpw的属性

      来引用字段
      <form:input path="name" /> 
      <form:errors path="name" cssClass="error" />
      

      将更改为

      <form:input path="customer.name" /> 
        <form:errors path="customer.name" cssClass="error" />
      

      同样,对于产品验证,您可以使用

      <form:input path="product.productName" /> 
      <form:errors path="product.productName" cssClass="error" />
      

      就是这样。