MVC:下拉菜单中的值未设置为所选值-保持为0

时间:2019-05-18 00:25:04

标签: java spring-boot spring-mvc drop-down-menu thymeleaf

这是一个使用thymeleaf模板管理器的Spring Boot应用程序。它具有一个简单的带有下拉菜单的表单。选项是从数据库中填充的,它们的名称(或ID)都可以在表单上正确显示,但是在选择选项并提交给定所选变量的表单值后,其值仍为0

虽然我获得了变量content的正确值,但是categoryId在提交后始终为0(如果将其类型从int更改为Integer,则为null)。

我猜测该模型未正确“链接”到jokeForm,但我不知道如何正确链接它。我正在关注example 1。我希望有人可以通过快速查看我的代码来轻松发现问题。代码在方法submitForm()中中断。

HTML表单:

        <html>
        <body>
        <form action="#" th:action="@{/new}" th:object="${jokeForm}" method="post"> 
            <table>
                <tr>
                    <td>Content:</td>
                    <td><input type="text" th:field="*{content}" /></td>
                    <td th:if="${#fields.hasErrors('content')}" th:errors="*{content}">Content Error</td>
                </tr>
                <tr>
                    <td>Category:</td>
                    <td>
                        <select name="categoryId" th:field="*{categoryId}">
                         <option  value="0" th:each="category : ${categories}"
                            th:value="${category.id}"
                            th:utext="${category.name}"/>
                         <!-- <option th:each="category : *{categories}"
                            th:value="*{category.id}"
                            th:utext="*{category.name}"/> -->
                         </select>
                    </td>
                    <td th:if="${#fields.hasErrors('categoryId')}" th:errors="*{categoryId}">category Error</td>
                </tr>
               <tr> 
                    <td><button type="submit">Submit</button></td>
                </tr>
            </table>
        </form>
    </body>
</html>

控制器

    @GetMapping("/new")
    public String showForm( Model model) {
       DEBUG("showForm");
       JokeForm form = new JokeForm();
       categories = categoryRepository.findAll();


       DEBUG(categories.get(0).toString());
       DEBUG(categories.get(1).toString());

       //form.setCategories(categories); //not working
       model.addAttribute("jokeForm", form);          
       model.addAttribute("categories",categories);

       return "form";
    }


    @PostMapping("/new")
    @ResponseBody
    public String submitForm(@ModelAttribute JokeForm jokeForm) {
        DEBUG("submitForm");
        //String content = jokeForm.getContent();
        DEBUG(jokeForm.getContent());
        DEBUG(jokeForm.getCategoryId().toString());


        Joke j = new Joke();
        j.setContent(jokeForm.getContent());
        //j.setCategoryId(jokeForm.getCategoryId());

        //DEBUG(Integer.toString(jokeForm.getCategoryId()));
//CAUSES ERROR value of CategoryId is Integer -> null       System.out.println(Integer.toString(jokeForm.getCategoryId())); 
//PRODUCES ERROR value of CategorId is int (because no category matches)        j.setCategory(categoryRepository.findById(jokeForm.getCategoryId().intValue()).get(0));

jokeRepository.save(j); //save

        return "Saved";
    }

JokeForm

        public class JokeForm {


    @NotEmpty(message = "content may not be empty")
    private String content;

    @NotEmpty(message = "category may not be empty") 
    private int categoryId; //int-> 0, Integer -> null

        /*
    @NotEmpty(message = "category may not be empty") 
    private Category category;

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    private List<Category> categories;
    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    } */

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategory(Integer categoryId) {
        this.categoryId = categoryId;
    }

}

1 个答案:

答案 0 :(得分:0)

您为所有选项设置了value="0"

<select>应该是:

<select th:field="*{categoryId}">
   <option th:each="category : ${categories}"
      th:value="${category.id}"
      th:utext="${category.name}"/>
      <!-- <option th:each="category : *{categories}"
         th:value="*{category.id}"
         th:utext="*{category.name}"/> -->
</select>

编辑: 并在JokeForm类中添加(设置)setCategoryId()