2016-09-20 198 views
0

使用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)... 
+0

如果您在前端使用Spring表單,請將'@ RequestBody'更改爲'@ ModelAttribute'如果可能,請顯示前端代碼(如何調用此請求) –

+0

這是一個REST端點,所以我只是使用郵差客戶端在主體中使用JSON對象進行POST。 – tlavarea

+0

[this](http://blog.codeleak.pl/2013/09/request-body-validation-in-spring-mvc-3.2.html)和[此鏈接](https://dzone.com/articles/spring-31-valid-requestbody)可能對你有所幫助 –

回答

0

使用@Valid註釋應聲明BindingResult參數正確驗證後POJO。 BindingResult會包含所有的驗證錯誤,你可以隨意做任何你想要的事情。

+1

更多上下文:[入門 - 驗證表單輸入](https://spring.io/guides/gs/validating-form-input/)。入門說明了如何進行表單驗證,但您也可以根據JSON請求執行您自己的自定義響應。 –

+0

謝謝你的迴應。我已經嘗試過,沒有任何運氣。 BindingResult始終包含零錯誤。我也嘗試創建一個@ContainerAdvice類來全局處理MethodArgumentNotValidException和ConstraintViolationException,但這也沒有奏效。 – tlavarea

+0

嘗試從您的參數中刪除@RequestBody註釋,並確保您的類路徑中具有javax.validation的實現,例如休眠驗證器。 你在哪裏放置了BindingResult?這是後驗證的param,就像這樣:'(@Valid MyPojo pojo,BindingResult錯誤,@Valid MyAnotherPojo anotherPojo,BindingResult anotherErrors)' –

0

所以事實證明,@BasePathAwareController是什麼導致綁定驗證不運行。不知道這是預期行爲還是錯誤,但是通過從控制器中刪除該註釋,驗證按預期運行。