使用Spring Boot 1.4和Spring Data Rest/MVC我無法獲得@Valid @RequestBody的工作。我已經嘗試過多個版本的Hibernate Validator,聲明Validator beans等。沒有運氣。春季休眠驗證@RequestBody
@BasePathAwareController
@RestController
public class TestRestController extends BaseController {
@PostMapping("/pojo/save")
public @ResponseBody ResponseEntity<?> upload(@Valid @RequestBody MyPojo pojo) {
// Code here calling a repository.save.
}
MyPojo包含各種驗證註解即@digits,@NotNull,等我真正看到驗證異常時repostiory.save方法被調用,但春節不試圖對POJO任何驗證。
這裏是我的POM的包括彈簧的依賴部分:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
任何想法,將不勝感激。我做了大量的搜索,並嘗試了許多不同的配置,沒有任何運氣。
更新
當試圖將實體保存到數據庫中,發生的驗證錯誤時的。我收到以下錯誤:
Caused by: javax.persistence.RollbackException: Error while committing the transaction
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='numeric value out of bounds (<9 digits>.<3 digits> expected)...
如果您在前端使用Spring表單,請將'@ RequestBody'更改爲'@ ModelAttribute'如果可能,請顯示前端代碼(如何調用此請求) –
這是一個REST端點,所以我只是使用郵差客戶端在主體中使用JSON對象進行POST。 – tlavarea
[this](http://blog.codeleak.pl/2013/09/request-body-validation-in-spring-mvc-3.2.html)和[此鏈接](https://dzone.com/articles/spring-31-valid-requestbody)可能對你有所幫助 –