[英]Spring MVC Bean Validation with Java Configuration
我正在为Spring MVC使用Java配置。 我无法使Bean验证正常工作。 我有一个已注释的域类,并且想在Controller中使用@Valid
。 我知道使用XML配置时,我将以这种方式设置验证器<mvc:annotation-driven validator="validator"/>
如何使用Java配置执行此操作。 我没有收到任何错误,验证只是行不通。 提前致谢!
这是我的设置:
带有注释的域类:
public class Product {
@Pattern(regexp="P[1-9]+", message="{Pattern.Product.productId.validation}")
@ProductId
private String productId;
@Size(min=4, max=50, message="{Size.Product.name.validation}")
private String name;
@Min(value=0, message="Min.Product.unitPrice.validation}")
@Digits(integer=8, fraction=2, message="{Digits.Product.unitPrice.validation}")
@NotNull(message= "{NotNull.Product.unitPrice.validation}")
private BigDecimal unitPrice;
private String description;
private String manufacturer;
private String category;
private long unitsInStock;
这是我使用@Valid的控制器:
@Controller
@RequestMapping("/products")
public class ProductController {
..... (shortened)
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String getAddNewProductForm(@ModelAttribute("newProduct") Product newProduct) {
return "addProduct";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String processAddNewProductForm(@ModelAttribute("newProduct") @Valid Product productToBeAdded, BindingResult result, HttpServletRequest request) {
if(result.hasErrors()) {
return "addProduct";
}
String[] suppressedFields = result.getSuppressedFields();
if (suppressedFields.length > 0) {
throw new RuntimeException("Attempting to bind disallowed fields: " + StringUtils.arrayToCommaDelimitedString(suppressedFields));
}
MultipartFile productImage = productToBeAdded.getProductImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
if (productImage!=null && !productImage.isEmpty()) {
try {
productImage.transferTo(new File(rootDirectory+"resources\\images\\"+productToBeAdded.getProductId() + ".png"));
} catch (Exception e) {
throw new RuntimeException("Product Image saving failed", e);
}
}
productService.addProduct(productToBeAdded);
return "redirect:/products";
}
这是我的@EnableWebMVC的Config类:( ***更新为获取验证器*** )
@SuppressWarnings("deprecation")
@Configuration
@ComponentScan(basePackages = {"com.nam.webstore"})
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
..... (shortened)
@Bean(name = "validator")
public LocalValidatorFactoryBean localValidatorFactoryBean() {
LocalValidatorFactoryBean lvfb = new LocalValidatorFactoryBean();
lvfb.setValidationMessageSource(resourceBundleMessageSource());
return lvfb;
}
(***** Updated *****)
@Override
public Validator getValidator() {
return localValidatorFactoryBean();
}
}
这是带有错误标记的jsp:
..... (shortened)
<section class="container">
<form:form modelAttribute="newProduct" class="form-horizontal" enctype="multipart/form-data">
<fieldset>
<legend>Add new product</legend>
<form:errors path="*" cssClass="alert alert-danger" element="div"/>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="productId"><spring:message code="addProduct.form.productId.label"/></label>
<div class="col-lg-10">
<form:input id="productId" path="productId" type="text" class="form:input-large"/>
<form:errors path="productId" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="name"><spring:message code="addProduct.form.name.label"/></label>
<div class="col-lg-10">
<form:input id="name" path="name" type="text" class="form:input-large"/>
<form:errors path="name" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="unitPrice"><spring:message code="addProduct.form.unitPrice.label"/></label>
<div class="col-lg-10">
<div class="form:input-prepend">
<form:input id="unitPrice" path="unitPrice" type="text" class="form:input-large"/>
<form:errors path="unitPrice" cssClass="text-danger"/>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="description"><spring:message code="addProduct.form.description.label"/></label>
<div class="col-lg-10">
<form:textarea id="description" path="description" rows = "2"/>
</div>
</div>
更新 将Logger设置为DEBUG之后,这就是我在控制台中看到的内容。 我可以看到它正在启动验证,但是我不知道为什么要向DispatcherServlet返回null? 我要返回视图名称。
字段“ unitPrice”上对象“ newProduct”中的字段错误:拒绝的值[null]; 代码[NotNull.newProduct.unitPrice,NotNull.unitPrice,NotNull.java.math.BigDecimal,NotNull]; 参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[newProduct.unitPrice,unitPrice]; 参数[]; 默认消息[unitPrice]]; 默认消息[单价无效。 它不能为空。]字段'productId'上的对象'newProduct'中的字段错误:拒绝的值[]; 代码[Pattern.newProduct.productId,Pattern.productId,Pattern.java.lang.String,Pattern]; 参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[newProduct.productId,productId]; 参数[]; 默认消息[productId],[Ljavax.validation.constraints.Pattern $ Flag; @ 3641ef8a,P [1-9] +]; 默认消息[无效的产品ID。 它应以字符P开头,后跟数字。]字段“名称”上的对象“ newProduct”中的字段错误:拒绝的值[]; 代码[Size.newProduct.name,Size.name,Size.java.lang.String,Size]; 参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[newProduct.name,name]; 参数[]; 默认消息[名称],50,4]; 默认消息[无效的产品名称。 它应至少为4个字符,最多为50个字符。] 2014-07-25 15:03:36 DEBUG ResponseStatusExceptionResolver:134-解决处理程序中的异常[公共java.lang.String com.nam.webstore.controller.ProductController.processAddNewProductForm (com.nam.webstore.domain.Product,org.springframework.ui.ModelMap,org.springframework.validation.BindingResult,javax.servlet.http.HttpServletRequest)]:org.springframework.validation.BindException:org.springframework.validation .BeanPropertyBindingResult:3个错误字段'unitPrice'上的对象'newProduct'中的字段错误:拒绝的值[null]; 代码[NotNull.newProduct.unitPrice,NotNull.unitPrice,NotNull.java.math.BigDecimal,NotNull]; 参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[newProduct.unitPrice,unitPrice]; 参数[]; 默认消息[unitPrice]]; 默认消息[单价无效。 它不能为空。]字段'productId'上的对象'newProduct'中的字段错误:拒绝的值[]; 代码[Pattern.newProduct.productId,Pattern.productId,Pattern.java.lang.String,Pattern]; 参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[newProduct.productId,productId]; 参数[]; 默认消息[productId],[Ljavax.validation.constraints.Pattern $ Flag; @ 3641ef8a,P [1-9] +]; 默认消息[无效的产品ID。 它应以字符P开头,后跟数字。]字段“名称”上的对象“ newProduct”中的字段错误:拒绝的值[]; 代码[Size.newProduct.name,Size.name,Size.java.lang.String,Size]; 参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[newProduct.name,name]; 参数[]; 默认消息[名称],50,4]; 默认消息[无效的产品名称。 它应该至少为4个字符,最多为50个字符。] 2014-07-25 15:03:36 DEBUG DefaultHandlerExceptionResolver:134-解决处理程序中的异常[公共java.lang.String com.nam.webstore.controller.ProductController.processAddNewProductForm (com.nam.webstore.domain.Product,org.springframework.ui.ModelMap,org.springframework.validation.BindingResult,javax.servlet.http.HttpServletRequest)]:org.springframework.validation.BindException:org.springframework.validation .BeanPropertyBindingResult:3个错误字段'unitPrice'上的对象'newProduct'中的字段错误:拒绝的值[null]; 代码[NotNull.newProduct.unitPrice,NotNull.unitPrice,NotNull.java.math.BigDecimal,NotNull]; 参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[newProduct.unitPrice,unitPrice]; 参数[]; 默认消息[unitPrice]]; 默认消息[单价无效。 它不能为空。]字段'productId'上的对象'newProduct'中的字段错误:拒绝的值[]; 代码[Pattern.newProduct.productId,Pattern.productId,Pattern.java.lang.String,Pattern]; 参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[newProduct.productId,productId]; 参数[]; 默认消息[productId],[Ljavax.validation.constraints.Pattern $ Flag; @ 3641ef8a,P [1-9] +]; 默认消息[无效的产品ID。 它应以字符P开头,后跟数字。]字段“名称”上的对象“ newProduct”中的字段错误:拒绝的值[]; 代码[Size.newProduct.name,Size.name,Size.java.lang.String,Size]; 参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[newProduct.name,name]; 参数[]; 默认消息[名称],50,4]; 默认消息[无效的产品名称。 它应至少为4个字符,最多为50个字符。] 2014-07-25 15:03:36 DEBUG DispatcherServlet:1012-空ModelAndView返回到DispatcherServlet,名称为'DispatcherServlet':假设HandlerAdapter完成了请求处理2014-07-25 15 :03:36 DEBUG DispatcherServlet:991-成功完成请求
在您的WebMvcConfigurerAdapter
您可以重写getValidator()
方法以使其返回自定义的Validator
。
使用LocalValidatorFactoryBean
,您可以调用afterPropertiesSet()
和getObject()
来获取真实的Validator
。
老主题,但我有同样的问题,所以我将这个豆粘贴
@Override
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.