spring 如何将ModelAttribute从HTML(Thymeleaf)发送到控制器

n3schb8v  于 2023-10-15  发布在  Spring
关注(0)|答案(2)|浏览(102)

我的BookController:

@GetMapping("/{id}")
public String showBook(Model model, @PathVariable("id") Integer id, @ModelAttribute("review") Review review){
    if(bookService.findOne(id).isPresent()) {
        model.addAttribute("book", bookService.findOne(id).get());
        System.out.println(SecurityContextHolder.getContext().getAuthentication().getName());
        model.addAttribute("currentUser", SecurityContextHolder.getContext().getAuthentication().getName());
        return "/books/show";
    }
    return "redirect:/books";
}

我想把这个当前Book对象发送到CardController并在CardController中获取它。我怎么能做到呢?
我做了一个表单,但我不知道如何发送对象

<form th:unless="${#strings.equals(currentUser, 'anonymousUser')}" th:method="POST" th:action="@{/card}">
<button id="add-button" class="fw primary" type="submit">Add book to the card.</button>
</form>
z0qdvdin

z0qdvdin1#

您已经将showBook()建模为GET方法,因此您不需要或不想使用表单和POST,链接将完成任务,并且更合适。试试看:

<a id="add-button" class="fw primary" th:href="@{/books/{id}(id=${book.id})}">Add book to the card.</a>

这假设您在控制器类上有@RequestMapping(“/books”),并且您从中创建链接的页面可以访问模型中具有id属性的书籍。
如果你想要一个按钮而不是一个链接的风格,相应的链接.

snz8szmq

snz8szmq2#

<form th:unless="${#strings.equals(currentUser, 'anonymousUser')}" th:method="POST" th:action="@{/card}">
<button id="add-button" class="fw primary" type="submit" th:value="${book.id}">Add book to the card.</button>
</form>


@GetMapping("/card/{id}")
    public String showBook(Model model, @PathVariable("id") Integer id, @ModelAttribute("review") Review review){
        if(bookService.findOne(id).isPresent()) {
            model.addAttribute("book", bookService.findOne(id).get());
            System.out.println(SecurityContextHolder.getContext().getAuthentication().getName());
            model.addAttribute("currentUser", SecurityContextHolder.getContext().getAuthentication().getName());
            return "/books/show";
        }
        return "redirect:/books";
    }

相关问题