java - 在 GET 请求中使用 LocalDate 作为参数的 TypeMismatch 错误
问题描述
我有一个带有 3 个属性的过滤器类来搜索可用的书籍。我有两个搜索案例:搜索书籍代码列表或按日期搜索。
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class BookFilter {
Set<Long> bookCodes;
LocalDate fromDate;
LocalDate toDate;
}
这是我的控制器
@GetMapping("/books")
public ResponseEntity<Page<BookView>> findAvailableBooks(BookFilter bookFilter, Pageable pageable) {
Page<Book> page = service.findAvailableBooks(bookFilter);
Page<BookView> map = page.map(book-> modelMapper.map(book, BookView.class));
return ResponseEntity.status(HttpStatus.OK).body(map);
}
我正在尝试在 Postman 中发送请求,例如:
http://localhost:8887/v1/api/library/books?fromDate=01-01-2019&toDate=01-31-2019
但我陷入了 typeMismatch 错误:无法从 String 类型转换为 LocalDate。我错过了什么?
解决方案
/* 1. Get as String */
@GetMapping("/books")
ResponseEntity<Page<BookView>> findAvailableBooks(@RequestParam(value = "fromDate", required = false) String fromDate, @RequestParam(value = "toDate", required = false) String toDate, Pageable pageable) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate fromLocalDate = LocalDate.parse(fromDate, formatter);
LocalDate toLocalDate = LocalDate.parse(toDate, formatter);
// other code
}
/* 2. Using @DateTimeFormat */
@GetMapping("/books")
ResponseEntity<Page<BookView>> findAvailableBooks(@RequestParam(value = "fromDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime fromDate, @RequestParam(value = "toDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime toDate, Pageable pageable) {
// other code
}
使用 @RequestParam 将 LocalDate 作为字符串发送,然后将其转换为所需的日期格式
在日期参数中使用所需格式的 @DateTimeFormat (iso = DateTimeFormat.ISO.DATE_TIME)
此外,之前在此主题上提出了一个非常相似的问题:
如何在 Spring 中使用 LocalDateTime RequestParam?我收到“无法将字符串转换为 LocalDateTime”
推荐阅读
- sql - 如何根据其他列的值更新列
- html - 颜色被覆盖,但css中的文本装饰
- angular - 离子选择和离子日期时间的离子通过值计算
- javascript - 如何使用嵌套过滤器来检测是否只有一个 li 以及它的孩子是否只有
- flutter - 使用文本字段作为按钮
- android-studio - 列表视图解决方案
- text-to-speech - 如何在 Azure Direct Line Speech 机器人中使用神经语音
- php - 比较两个不同结构化数组中的数组元素
- javascript - 如何在angularjs中一起使用默认排序和自定义排序
- android - 在 Android 中使用应用内更新时如何解决安装状态码 -100?