当传递一个 id 时,我的视图显示一个奇怪的结果

When passed an id, my view displays a strange result

所以我想从我的 index.html 页面上的列表中单击一个 link,将一个 id 传递给控制器​​,该 id 由视图接收,显示单个数据库条目。然而这只显示这个;

project.whatscookin.models.data.forms.Recipe@2ff936c5 project.whatscookin.models.data.forms.Recipe@2ff936c5 *Recipe@后面的数字每次刷新都会改变。

控制器;

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

和视图,food.html;

<table class="table">

<tr>
    <th>Name</th>

</tr>

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

编辑 食谱 Class;

@Entity

public class 食谱 {

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

}

您可以尝试使用以下结构构建您的 href。这应该会给你想要的 url.

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

更新

好的,我相信我找到了你的问题。请进行以下更改。

控制器

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

问题是,在你最后的方法中,你没有显示对象的属性,而是它的签名。因此,当您使用 ${name} 时,您实际上是在发送对对象的引用,而不是它的字段。

这是 toString() 的默认实现。如果你想要别的东西,你应该在你的 Recipe class.

中覆盖这个方法