Search code examples
javahtmlspring-bootthymeleafmamp

When passed an id, my view displays a strange result


So i want to click a link from a list on my index.html page, passing an id to the controller, which is received by a view, displaying the single database entry. However this only displays this;

project.whatscookin.models.data.forms.Recipe@2ff936c5 project.whatscookin.models.data.forms.Recipe@2ff936c5 *the numbers after Recipe@ change each refresh.

Controller;

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

}

Index.html;

<table class="table">

<tr>
    <th>Name</th>

</tr>

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

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

And the view, food.html;

<table class="table">

<tr>
    <th>Name</th>

</tr>

<h4 th:text="${name}"></h4>
<span th:text="${recipeText}"></span>

EDIT Recipe Class;

@Entity

public class Recipe {

@Id
@GeneratedValue
private int id;

@NotNull
@Size(min=3, max=15)
private String name;

@NotNull
@Size(min=1, message = "Recipe text must not be empty")
private String recipeText;

public Recipe() {

}

public Recipe(String name, String recipeText) {
    this.name = name;
    this.recipeText = recipeText;

}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getRecipeText() {
    return recipeText;
}

public void setRecipeText(String recipeText) {
    this.recipeText = recipeText;
}

}


Solution

  • You can try building your href using the following structure. This should give you the desired url.

    <a th:href="@{'/food/' + ${recipe.id}}">view</a>
    

    Update

    Ok, I believe I found your problem. Please, make the following changes.

    Controller

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

    food.html

    <table class="table">
    <tr>
        <th>Name</th>
    </tr>
    <h4 th:text="${recipe.name}"></h4>
    <span th:text="${recipe.recipeText}"></span>
    

    The thing is that in your last approach, you weren't displaying the object's attributes, but it's signature. So, when you used ${name}, you were actually sending referencing the object and not it's field.