Spring中@Pattern的使用

Controller層

@RestController
@Validated
class Controller {
  // ...
}

爲Controller添加@Validated表示啓用驗證。正則表達式

@GetMapping
public ResponseEntity<List<Permission>> query(@RequestHeader("iv-user") String userId,
                                                  @Pattern(regexp = "^accessor$", message = "請求參數不合法")
                                                  @RequestParam("findBy") String accessor,
                                                  @RequestParam("accessorId") long accessorId){
        //...
}

爲Controller中特定請求添加@Pattern(regexp = "^accessor$", message = "請求參數不合法")正則表達式校驗。spring

Json響應

{
    "timestamp": "2018-07-19T02:08:01.372+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "query.accessor: 請求參數不合法",
    "path": "/budget/permissions"
}

總結

很方便,還能夠本身捕獲這個異常的對返回進行自定義處理。app

參考:

Spring Boot REST @RequestParam not being Validated spring-boot

相關文章
相關標籤/搜索