Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc 如果有两个模型对象数据,则验证表单_Spring Mvc - Fatal编程技术网

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

Spring mvc 如果有两个模型对象数据,则验证表单,spring-mvc,Spring Mvc,通常我在SpringMVC中看到过这样的服务器端验证,例如,有一个customer页面,其中包含与客户相关的信息,如customerName、customerAddress、customerPhoneNumber 客户模型对象,然后在spring控制器中,我们将这样调用 弹簧控制器 @RequestMapping(value = "/customerRegistrationScreen") public String customerRegistrationScreen(Model mo

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

弹簧控制器

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

   }

}
@组件
公共类CustomerValidator实现验证器{
@凌驾
公共布尔支持(类clazz){
返回Customer.class.equals(clazz);
}
@凌驾
公共无效验证(对象对象对象,错误错误){
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”);
用户=(用户)对象;
Pattern Pattern=Pattern.compile(“^[A-Z0-9.\%+-]+@[A-Z0-9.-]+\\[A-Z]{2,6}$”,
模式(不区分大小写);
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,会怎么样?这里我想有两个模型对象,如Customer
&产品如果我有两个模型对象,我如何从jsp和Spring contoller映射模型属性,以及如何对这两个验证进行服务器端验证尽管在每个表单中保持模型独立是一个好主意,但对于这个特定的用例,可以通过以下步骤来实现

实现这一点的最佳方法是将两个模型属性包装在一个包装器类中,并在验证中使用它

  • 让我们假设产品类是这样的

    公共类产品{

    字符串名称; //其他字段及其getter setter }

  • 创建一个包装类,该类包装两种型号
    客户
    产品

    公共类CustomerProductWrapper{

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

  • 在验证器类中,更改
    supports()
    方法的实现,如下所示

    @Override
       public void validate(Object obj, Errors err) {
    
    @凌驾 公共布尔支持(类clazz){ 返回CustomerProductWrapper.class.equals(clazz); }

  • 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");
    
       }
    
  • 在控制器映射中

    公共字符串CustomerRegistration屏幕(模型){ CustomerProductWrapper cpw=新CustomerProductWrapper(); model.addAttribute(“cpw”,cpw);
    返回“customerRegistrationScreen”; }

  • 最后是在您的查看页面中

    <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" />
    
    
    
    就这些