gpt4 book ai didi

java - 使用 Java 配置进行 Spring MVC Bean 验证

转载 作者:行者123 更新时间:2023-11-30 06:18:11 31 4
gpt4 key购买 nike

我正在为 Spring MVC 使用 Java 配置。我无法让 Bean Validation 工作。我有一个已注释的域类,我想使用 @Valid在我的 Controller 中。我知道使用 XML 配置,我会这样设置 validator <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 :

@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 的配置类:(***已更新以获取 validator ***)

@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 后,这就是我在控制台中看到的内容。我可以看到它正在触发验证,但我不知道为什么它说我要将 null 返回给 DispatcherServlet?我正在返回 View 名称。

Field error in object 'newProduct' on field 'unitPrice': rejected value [null]; codes [NotNull.newProduct.unitPrice,NotNull.unitPrice,NotNull.java.math.BigDecimal,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newProduct.unitPrice,unitPrice]; arguments []; default message [unitPrice]]; default message [Unit price is Invalid. It cannot be empty.] Field error in object 'newProduct' on field 'productId': rejected value []; codes [Pattern.newProduct.productId,Pattern.productId,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newProduct.productId,productId]; arguments []; default message [productId],[Ljavax.validation.constraints.Pattern$Flag;@3641ef8a,P[1-9]+]; default message [Invalid product ID. It should start with character P followed by number.] Field error in object 'newProduct' on field 'name': rejected value []; codes [Size.newProduct.name,Size.name,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newProduct.name,name]; arguments []; default message [name],50,4]; default message [Invalid product name. It should be minimum 4 characters to maximum 50 characters long.] 2014-07-25 15:03:36 DEBUG ResponseStatusExceptionResolver:134 - Resolving exception from handler [public 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 errors Field error in object 'newProduct' on field 'unitPrice': rejected value [null]; codes [NotNull.newProduct.unitPrice,NotNull.unitPrice,NotNull.java.math.BigDecimal,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newProduct.unitPrice,unitPrice]; arguments []; default message [unitPrice]]; default message [Unit price is Invalid. It cannot be empty.] Field error in object 'newProduct' on field 'productId': rejected value []; codes [Pattern.newProduct.productId,Pattern.productId,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newProduct.productId,productId]; arguments []; default message [productId],[Ljavax.validation.constraints.Pattern$Flag;@3641ef8a,P[1-9]+]; default message [Invalid product ID. It should start with character P followed by number.] Field error in object 'newProduct' on field 'name': rejected value []; codes [Size.newProduct.name,Size.name,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newProduct.name,name]; arguments []; default message [name],50,4]; default message [Invalid product name. It should be minimum 4 characters to maximum 50 characters long.] 2014-07-25 15:03:36 DEBUG DefaultHandlerExceptionResolver:134 - Resolving exception from handler [public 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 errors Field error in object 'newProduct' on field 'unitPrice': rejected value [null]; codes [NotNull.newProduct.unitPrice,NotNull.unitPrice,NotNull.java.math.BigDecimal,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newProduct.unitPrice,unitPrice]; arguments []; default message [unitPrice]]; default message [Unit price is Invalid. It cannot be empty.] Field error in object 'newProduct' on field 'productId': rejected value []; codes [Pattern.newProduct.productId,Pattern.productId,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newProduct.productId,productId]; arguments []; default message [productId],[Ljavax.validation.constraints.Pattern$Flag;@3641ef8a,P[1-9]+]; default message [Invalid product ID. It should start with character P followed by number.] Field error in object 'newProduct' on field 'name': rejected value []; codes [Size.newProduct.name,Size.name,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newProduct.name,name]; arguments []; default message [name],50,4]; default message [Invalid product name. It should be minimum 4 characters to maximum 50 characters long.] 2014-07-25 15:03:36 DEBUG DispatcherServlet:1012 - Null ModelAndView returned to DispatcherServlet with name 'DispatcherServlet': assuming HandlerAdapter completed request handling 2014-07-25 15:03:36 DEBUG DispatcherServlet:991 - Successfully completed request

最佳答案

在您的 WebMvcConfigurerAdapter 中,您可以覆盖 getValidator() 方法,让它返回您的自定义 Validator

使用 LocalValidatorFactoryBean,您可以调用 afterPropertiesSet()getObject() 来获得真正的 Validator .

关于java - 使用 Java 配置进行 Spring MVC Bean 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24957878/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com