如何使用 Spring Boot 将表单数据绑定到模型中?

我有这个表格:


<form action="/my-path" method="post">

    <div class="form-group">

        <label for="domain">Domain</label>

        <input class="form-control" id="domain" type="text" value="" name="domain">

        <label for="color">Color</label>

        <input class="form-control" id="color" type="text" value="" name="color">

    </div>

    <button class="btn btn-primary" type="submit">Filter</button>

</form>

我试图在 Spring MVC 中处理:


@PostMapping(

        path = ["/my-path"],

        produces = [MediaType.TEXT_HTML_VALUE])

public ResponseEntity<String> doSomething(ModelMap map) {

    // ...

}

但我就是无法正常工作,POST即使我用数据填写表格并提交,我也看不到任何数据。


我尝试将值绑定到我自己的 dto:


@PostMapping(

        path = ["/my-path"],

        produces = [MediaType.TEXT_HTML_VALUE])

public ResponseEntity<String> doSomething(@RequestBody MyDto dto) {

    // ...

}

但在这种情况下,我得到一个异常,因为该方法不受支持(url 编码形式)。我在这里不知所措,我尝试了 10 种不同的方法来从请求中获取表单数据,但它不起作用,我要么得到异常,要么根本没有得到任何数据。


如何使这个非常基本的用例与 Spring Boot 一起使用?


红颜莎娜
浏览 139回答 1
1回答

慕后森

如果想获取一个map中的所有请求参数,可以@RequestParam在函数中添加一个Map参数,像这样:@PostMapping(&nbsp; &nbsp; &nbsp; &nbsp; path = ["/my-path"],&nbsp; &nbsp; &nbsp; &nbsp; produces = [MediaType.TEXT_HTML_VALUE])public ResponseEntity<String> doSomething(@RequestParam Map allRequestParams) {&nbsp; &nbsp; // ...}如果你想在不同的变量中获取每个表单组件,你可以使用这样的东西:@PostMapping(&nbsp; &nbsp; &nbsp; &nbsp; path = ["/my-path"],&nbsp; &nbsp; &nbsp; &nbsp; produces = [MediaType.TEXT_HTML_VALUE])public ResponseEntity<String> doSomething(String domain, String color) {&nbsp; &nbsp; // ...}Spring 会自动将表单输入绑定到您的参数,使输入的“id”属性与参数名称相匹配。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java