Search code examples
javaspring-bootthymeleafmamp

Cannot display a result based on a database id when id is passed to view


<table class="table">

<tr>
    <th>Name</th>

</tr>

<tr th:each="recipe : ${recipes}">
    <td th:text="${recipe.Name}"></td>
    <td>
            <span th:each="recipe,iterStat : ${recipes}">

            </span>
    </td>
    <td>
        <a th:href="@{/recipe/food/{id}(id=${recipe.id})}">view</a>
    </td>
</tr>

I am trying to click this link above, utilizing this controller

    @RequestMapping(value="recipe/food/{id}", method = RequestMethod.POST)
public String viewRecipe(@PathVariable int id, Model model){
    model.addAttribute("name", recipeDao.findOne(id));
    model.addAttribute("recipeText", recipeDao.findOne(id));
    return "Recipes/food" ;
}

to display a single item, based on its id here

<table class="table">

<tr>
    <th>Name</th>

</tr>
<form method ="post" th:action="recipe/food/{id}" th:object=${recipe}">
<tr th:each="recipe : ${recipes}">

    <td th:text="${recipe.name}">text</td>
    <td th:text="${recipe.recipeText}">text</td>
</tr>

<span th:errors="*{recipeText}" class="error"></span>
</form>

however i only get a 404, but the url information is correct


Solution

  • When you click the link it will execute a GET-request, so try changing the method in the Controller to method = RequestMethod.GET or simply remove method = RequestMethod.POST.

    Update:

    The part of the food template that is in the third code snippet is looping over a list named recipes, but the Controller method isn't adding a list as an attribute to the model only "name" and "recipeText". What you want is probably the template to display the recipe that you clicked the link for? Something like <h4 th:text="${name}"></h4> <span th:text="${recipeText}" />