2015-03-03 68 views
1

我想在彈簧REST服務上自動驗證REST參數。如何自動驗證@RestController中的其餘參數?

我試過它使用@Valid @NotNull,但其餘的請求不會自動被拒絕,但dao方法是用null參數執行的。爲什麼?

@RestController 
public class RestController { 
    @RequestMapping(value = "/") 
    public Boolean getResponse(@Valid @NotNull @Length(max = 20) String username) { 
      return daoService.lookup(username); //is executed if username = null 
    } 
} 

我怎樣才能自動得到一個返回的HTTP錯誤,例如400?

+0

我認爲你只是缺少@RequestBody,雖然不知道春天可以驗證輸入字符串。 – mavarazy 2015-03-03 12:37:17

回答

1

這裏是關於請求參數的驗證的示例..

public ResponseEntity<AgencyResource> saveAgency(
    @Valid @RequestBody AgencyResource agencyResource) { 
return new ResponseEntity<AgencyResource>(agencyResource, HttpStatus.OK); 
} 

這是從POST http://www.leveluplunch.com/java/tutorials/017-validate-spring-rest-webservice-request/

希望這有助於。

感謝, 保羅

+0

所以我neccessairly必須包裹我的參數在一個複雜的對象?我想我也可以在字符串上實現驗證? – membersound 2015-03-03 12:40:42

+0

我不確定通過annotaiton對字符串進行簡單驗證。你也可以寫一個自定義的驗證..kinda like ..http://stackoverflow.com/questions/16544265/spring-3-mvc-request-validation – 2015-03-03 12:47:23

+1

你可能已經知道這..但是@RequestParam(value =「regNo 「,required = true)..你可以做到這一點..但是這隻要我知道只檢查所需的參數..不知道它是否可以做最小/最大長度檢查,除非你寫驗證。 – 2015-03-03 12:51:15