java - Spring Boot 不从 thymeleaf 返回值

标签 java spring web

我是 Spring boot 开发的新手,我试图找出为什么我的程序没有将值返回到 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

当我使用 get trough this 时。

http://localhost:8047/produto/lenco

但应该以 html 形式返回

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

最佳答案

您无法通过重定向来执行此操作。在重定向时,您的模型属性将丢失。

您有几个选择。

  1. 只需返回/static/produtos.html。除非您重定向到另一个 Controller ,否则重定向没有意义。

  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";
    }
    

关于java - Spring Boot 不从 thymeleaf 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52785237/

相关文章:

java - 如何在JSP中out.print() HTML属性?

java - 捕获内存不足错误的正确位置

Java/ Spring : "Tagging" beans in XML to get specific bean by class and tag

java - 捕获 Spring Integration DSL 错误配置异常?

c# - .Net 是否有任何 "dark launch"框架或库?

web - 如何知道我的网站被抓取了?

java - 使用递归从列表中获取所有组合,包括使用相同数字的组合

java - 在 OSGi 容器中为 Jersey-Grizzly 服务器内的 Rest 服务配置响应对象(使用 Jersey 1x 预防 CORS 错误)

spring - java.lang.NoClassDefFoundError : com/thoughtworks/xstream/io/naming/NameCode error in setting up restful webservice in spring 4. 3.1

python - 如何为 python 3.7 正确安装 Flask 以运行这个 github 项目?