首页 > 解决方案 > Spring Boot 不从 thymeleaf 返回值

问题描述

我是 Spring Boot Development 的新手,我试图找出为什么我的程序没有将值返回到 html。我尝试了很多例子都没有奏效。我将不胜感激。

    @GetMapping("/produto/{description}")
public String getLike(Model model,@PathVariable("description") String description){
    List<Produto> produtos =  (List<Produto>) productService.findLike(description);
    model.addAttribute("produtos",produtos);
    System.out.println(produtos);
    return "redirect:/static/produtos.html";
}

然后尝试重定向到这个..

<!DOCTYPE HTML>
 <html xmlns:th="http://www.thymeleaf.org">
 <head>
 <title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<tr th:each="produtos : ${produtos}">
<td><span th:text="${produtos.id}"></span></td>
<td><span th:text="${produtos.name}"></span></td>
<td><span th:text="${produtos.description}"></span></td>
<td><span th:text="${produtos.price}"></span></td>
</tr>

</html>

当我没有返回模型时,我通过 json 客户端返回一个列表,它可以工作并返回所有内容。但是当它是一个模型时。它不起作用并返回这个......

 redirect:/static/produtos.html

当我使用得到低谷这个。

http://localhost:8047/produto/lenco

但应该在 html 中返回这个

[
{
    "id": "223334455",
    "name": "lonco",
    "description": "lenco",
    "price": 83223
}
]

标签: javaspringweb

解决方案


你不能通过重定向来做到这一点。在重定向时,您的模型属性会丢失。

你有几个选择。

  1. 刚回来/static/produtos.html。除非您重定向到另一个控制器,否则重定向没有意义。

  2. RedirectAttributes在您的请求方法中使用。

    public String getLike(Model model, @PathVariable("description") String 
       description, RedirectAttributes redirectAttributes){
       List<Produto> produtos =  (List<Produto>)productService.findLike(description);
       redirectAttributes.addFlashAttribute("produtos",produtos);
       return "redirect:/static/produtos.html";
    }
    

推荐阅读