[英]Spring MVC/hibernate Form validation, not returning to form
我目前正在使用 Hibernate 和 Spring MVC 进行一些 HTML 表单验证。
我已经对 Enity 应用了一些验证并将代码添加到我的控制器中。 将包含格式不正确数据的表单提交给控制器时,将显示错误页面页面 (500)。 但是,我希望将表单返回给用户,并在不正确的字段附近显示错误消息。
实体代码:
@NotNull(message="Please enter a product")
@Column(name="product_name")
private String productName;
@NotNull(message="Please enter a product code")
@Pattern(regexp="([A-Z]{2,4})-([0-9]{5})|", message="Incorrect format")
@Column(name="product_code")
private String productCode;
控制器代码:
@GetMapping("/showFormForAdd")
public String showFormForAdd(Model theModel) {
// create model attribute to bind form data
QaRaised theProduct = new QaRaised();
theModel.addAttribute("product", theProduct);
return "product-form";
}
@PostMapping("/saveProduct")
public String saveProduct(@Valid @ModelAttribute("product") QaRaised theProduct, BindingResult bindingResult) {
qaRaisedService.saveProduct(theProduct);
if (bindingResult.hasErrors()) {
return "product-form";
}
return "redirect:/products/qaraised";
}
来自错误的堆栈跟踪:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [com.sonya.spring.entity.QaRaised] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[ConstraintViolationImpl{interpolatedMessage='Incorrect format', propertyPath=productCode, rootBeanClass=class com.sonya.spring.entity.QaRaised, messageTemplate='Incorrect format'}
表格代码:
<div class="form-group">
<label for="InputPC">Product Code:</label>
<form:input required="true" type="text" title="Product Code" path="productCode" class="form-control" id="productCodeInput" placeholder="Enter Product Code" commandName="productCode"/>
<form:errors path="productCode"/>
这里的验证工作正常,我只是想将用户重定向回表单。 谁能看到我遗漏的任何东西或为我指明正确的方向?
干杯,丹尼
这是一个老问题,但实际上我遇到了与您遇到的完全相同的编码问题的完全相同的问题,因此万一其他人遇到此问题...
@want2learn 是对的 - 在确保数据有效之前,您不应该尝试保存数据。 否则,验证器将抛出异常。 只需将您的保存逻辑向下移动:
@PostMapping("/saveProduct")
public String saveProduct(@Valid @ModelAttribute("product") QaRaised theProduct, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "product-form";
}
qaRaisedService.saveProduct(theProduct);
return "redirect:/products/qaraised";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.