java - 如何在 URI 行中将对象作为查询参数传递?
问题描述
你能帮我解释一下我应该如何传递作者值吗?
@GetMapping(value = "/search")
public ResponseEntity<List<Book>> searchBooksByTitleAndAuthor(
@RequestParam(value = "title", required = false) final String title,
@RequestParam(value = "author", required = false) final Author author) {
HttpStatus httpStatus = HttpStatus.OK;
List<Book> books = null;
if (title == null && author == null) {
log.info("Empty request");
httpStatus = HttpStatus.BAD_REQUEST;
} else if (title == null || author == null) {
books = bookService.getBooksByTitleOrAuthor(title, author);
} else {
Optional<Book> book = bookService.getBookByTitleAndAuthor(title, author);
if (book.isPresent()) {
books = Arrays.asList(book.get());
}
}
if (books == null) {
return new ResponseEntity<>(httpStatus);
} else {
return new ResponseEntity<>(books, httpStatus);
}
}
Author
看起来像这样的类:
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@EqualsAndHashCode
@ToString
public final class Author {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
private LocalDate dateOfBirth;
private String bio;
}
在这种情况下使用 author 或 @RequestParam 而不是请求正文是一种好方法吗?我考虑过只请求作为作者姓名的字符串,但这会影响服务的方法。
解决方案
根据https://lankydanblog.com/2017/03/11/passing-data-transfer-objects-with-get-in-spring-boot/,......你可以(在你设置一些转换注释之后author.dateOfBirth
) :
在字符串参数上使用
@RequestParam
(并让您的控制器/某人进行转换):..., @RequestParam(value = "author", required = false) final String author) { ...final Author author = new ObjectMapper().setDateFormat(simpleDateFormat) .readValue(author, Author.class);
在这种情况下,您会要求:
http://localhost:8080/myApp/search?title=foo&author={"id"="1",...}
或者:省略
@RequestParam
,但传递对象(让spring关心转换):...(@RequestParam(value = "title", required = false) final String title, final Author author)
并要求:
http://localhost:8080/myApp/search?title=foo&id=1&name=Donald E. Knuth&...
也可以看看:
推荐阅读
- python - 使用数据框值查询 SQL 数据库并附加回数据框
- python - “函数”对象没有属性“列”
- java - 我不知道为什么我会收到这样的错误消息 CLASS 不是抽象的并且不会覆盖抽象方法错误
- java - 多目标优化 Java
- django - 从视图中获取更多对象到模板中
- javascript - TypeIT 没有写完
- java - 如何在 oozie 工作流中的 java 操作中传递参数?
- python - 如何在整个代码中创建一个 while 循环。(Python)
- python - 需要帮助从多个大型 json 文件的 dask 对象中删除 None 行
- python - 使用 googletrans API 时如何修复 json.decoder.JSONDecodeError?