java - 如何将对象作为 URI 行中的查询参数传递?

标签 java spring spring-mvc model-view-controller

您能帮我解释一下我应该如何传递作者值吗?

@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 上设置一些转换注释后):

  1. 在字符串参数上使用@RequestParam(并让您的 Controller /某人 进行转换):

        ..., @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",...}
    
  2. 或者:省略@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&...
    

另请参阅:

关于java - 如何将对象作为 URI 行中的查询参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50429117/

相关文章:

java - 将数据从应用程序(Java)导入临时表的最快方法是什么?

java - Spring MVC : Getting date and time in specific format and persisting it

java - Extjs 4 和 sencha touch

java - JOptionPane 数组条件

java - 陷入 while (true) 循环内。如何在线程中隔离它?

java - 如何使用 Java-8 Streams 将 List 转换为 Map,其中 Key 是 ListValue,Value 是该特定列表的值的数量

java - Tomcat : NIOConnector throws exception

java - JPA:AttributeConverter 的参数化实例

java - Spring AOP 编程时出现奇怪的异常

java - 内嵌Tomcat的Jar和War打包的区别