Fel*_*wer 5 java rest spring spring-boot
当设置日期输入(required = false)但使用错误的正则表达式(fe 10-2019)时,我希望我的 RestController 返回错误
@GetMapping
@Timed
public ResponseEntity<ResponseBodyWrapper<List<ListData>>> getList(
@RequestParam(name = "date", required = false) @Pattern(regexp = "[0-9]{4}-[0-9]{1,2}") String date) {
// Logic
}
Run Code Online (Sandbox Code Playgroud)
但是,验证并未进行。我期待一个错误,但没有抛出任何错误,当我尝试使用错误的输入构建一个新对象时,错误发生了
@Validated当您希望触发验证时,控制器类必须使用以下注释@Validated:
@Validated\n@RestController\npublic class MyController {\n ...\n}\nRun Code Online (Sandbox Code Playgroud)\n\n引用文档:
\n\n\n\n\n为了符合 Spring 驱动的方法验证的条件,所有目标类都需要使用 Spring\xe2\x80\x99s
\n@Validated注释进行注释。
@Timed我发现你的控制器方法用 注释这一事实很奇怪@Timed。这是特定于测试的注释,并不意味着在实际代码中使用:
\n\n\n特定于测试的注释,指示测试方法必须在指定时间段内完成执行。
\n
您可能还想检查您的依赖项并确保它们使用正确的范围。
\n\nYearMonth而不是String由于您似乎在控制器方法中收到了年份和月份值,因此最好使用YearMonth而不是String:
\n\n\nISO-8601 日历系统中的年月,例如
\n2007-12。
你的控制器方法可以是这样的:
\n\n@GetMapping\npublic ResponseEntity<Foo> getList(@RequestParam(name = "date", required = false) YearMonth date) {\n ...\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
4390 次 |
| 最近记录: |