【问题标题】:Thymeleaf - Spring MVC. Form backing bean with boolean and checkboxesThymeleaf - Spring MVC。带有布尔值和复选框的表单支持 bean
【发布时间】:2015-09-25 15:01:51
【问题描述】:

我正在尝试使用百里香叶向弹簧控制器发布一个简单的表单。支持 bean 包含一个布尔值,该值使用 th:object 标记内的 th:field 映射到模板中的复选框。当我查看呈现的 html DOM 时,spring mvc 正在添加一个隐藏的输入字段,其中名称为 _attributeName。主输入字段的名称生成为attributeName。现在,当我尝试发布表单时,它会以 400 中止,因为请求参数 _attributeName 无法映射到支持 bean 对象(根本不存在)。因此,除了请求之外,还包括属性名称以及 _attributeName。为什么会这样?

【问题讨论】:

  • 如果他们没有看到任何代码,人们更有可能会忽略您的问题。

标签: java spring spring-mvc thymeleaf


【解决方案1】:

所以我终于解决了。问题是,我使用布尔值而不是布尔值,而我的 getter 命名为 isEnabled 而不是 getEnabled。这似乎导致了表单元素和支持 bean 之间的映射问题。

【讨论】:

  • 你的帖子为我节省了几个小时。不过我想补充一点,我只有在创建 getIsEnabled 样式的 getter 后才让我的复选框起作用。
  • 你能发布一个最小的例子吗,即控制器,模板,带有一个只有复选框和提交的表单和一个只有布尔值的支持 bean?
  • 你的帖子为我节省了几个小时。我使用布尔值而不是布尔值
  • 救命先生,不知道这东西出了什么问题。
【解决方案2】:

Vinc 提到的尝试过的解决方案,但对我不起作用。但是下面对我有用。

控制器

@Controller
public class BaseController {

    @GetMapping("/")
    private String index(DemoDto demoDto){
        return "index";
    }

    @PostMapping("/")
    private String receiveValues(DemoDto demoDto) {
        System.out.println(demoDto);
        return "index";
    }

}

DTO

public class DemoDto {
    private String name;
    private boolean global;

    //getter setter for name

    public boolean isGlobal() {
        return global;
    }
    public void setGlobal(boolean global) {
        this.global = global;
    }

    //toString()
}

HTML

<body>
    <form th:action="@{/}" th:method="post" th:object="${demoDto}">
        <label>Enter Name:</label> 
            <input type="text" th:field="*{name}" name="name"> 
        <br/>
        <label>Global</label>
            <input type="checkbox" th:field="${demoDto.global}"/>
        <input type="submit" value="Submit">
    </form>

</body>

这里最重要的是你如何定义th:field="${demoDto.global}"$ 和对象名称 demoDto 都是必需的。

会生成html代码。

<body>
    <form action="/" method="post">
        <label>Enter Name:</label> 
            <input type="text" name="name" id="name" value=""> 
        <br/>
        <label>Global</label>
            <input type="checkbox" id="global1" name="global" value="true"/>
            <input type="hidden" name="_global" value="on"/>
        <input type="submit" value="Submit">
    </form>

</body>

从 ui 提交时收到:

DemoDto [name=Dev, global=true]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2016-03-13
    • 2014-08-31
    • 2016-05-27
    相关资源
    最近更新 更多