java - MVC : Value in dropdown menu doesn't set to selected value - remains 0

标签 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>

Controller

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

笑话表单

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

}

最佳答案

您设置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>

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

关于java - MVC : Value in dropdown menu doesn't set to selected value - remains 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56194998/

相关文章:

java - spring-hibernate事务不回滚

java - Spring Boot - 在应用程序启动期间/之前运行代码的正确方法?

jakarta-ee - Web 项目中的 ClassNotFoundException

java - (经济)份额图的图算法

java - 来自sheet.drawingPatriarch.getChildren()的空指针

java - UsernamePasswordAuthenticationFilter 与自己的端点

java - 如何捕获 AuthenticationProvider 抛出的正确异常?

java - 如何在运行时修改 Camel 端点

java - 在 Java 中使用带有字符串和整数的 HashMap 时遇到问题

java - 由 : com. fastxml.jackson.core.JsonParseException : Unrecognized token 'Employee' : was expecting ('true' , 'false' 或 'null' 引起的错误)