Sherlocker
Sherlocker

Reputation: 355

Spring boot not returning values from thymeleaf

I'm new to Spring boot Development and I'm trying to find out why my program isnt returning the values to html. I tried a lot of examples none worked. I would appreciate the help.

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

And then try to redirect to this..

<!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>

When instead of returning the model I return a list trough a json client it works and returns everything. But when it's a model. It doesnt work and returns this...

 redirect:/static/produtos.html

When i use get trough this.

http://localhost:8047/produto/lenco

But should return this in html

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

Upvotes: 0

Views: 425

Answers (1)

Christopher Schneider
Christopher Schneider

Reputation: 3915

You can't do this with a redirect. On a redirect, your model attributes are lost.

You have a couple options.

  1. Just return /static/produtos.html. A redirect doesn't make sense unless you're redirecting to another controller.

  2. Use RedirectAttributes in your request method.

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

Upvotes: 2

Related Questions