你能帮我解释一下如何传递作者价值吗?
@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代替请求正文是一种好方法吗? 我想过只请求作为作者姓名的字符串,但它会影响服务的方法。
答案 0 :(得分:2)
根据https://lankydanblog.com/2017/03/11/passing-data-transfer-objects-with-get-in-spring-boot/,...您可以(在author.dateOfBirth
上设置一些转换注释后):
对String参数使用@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
,但是传递对象(让春天关心转换):
...(@RequestParam(value = "title", required = false) final String title,
final Author author)
并请求:
http://localhost:8080/myApp/search?title=foo&id=1&name=Donald E. Knuth&...
另见: