【问题标题】:Spring RestController POST accepting a basic HTML formSpring RestController POST 接受基本的 HTML 表单
【发布时间】:2020-01-21 23:15:38
【问题描述】:

我正在尝试使用 @ModelAttribute 和 MediaType.APPLICATION_FORM_URLENCODED_VALUE 作为消费数据类型将简单的 HTML 表单发布到 Spring RestController。我已经仔细检查了与我的请求 bean 匹配的所有表单字段。

当请求进入映射方法时,所有的请求bean字段都是空的。

@RestController
@EnableWebMvc
public class WebServiceController {

    @RequestMapping(
        value = "/test", 
        method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<?> post(@ModelAttribute FormBean request){
        // request.getParam() == null   
        return ResponseEntity.ok().build();
    }
}
public class FormBean {

    private String param1;

    public String getParam1() {
        return param1;
    }

    public void setParam1(String param1) {
        this.param1 = param1;
    }

}
<html>
    <head>
        <title>Test Form</title>
    </head>
    <body>
        <form action="/test" method="POST">
            <input type="text" id="param1">
            <button type="submit">Submit</button>
        </form>
    </body>
</html>

【问题讨论】:

    标签: java spring spring-boot spring-mvc spring-restcontroller


    【解决方案1】:

    您在 HTML 输入中缺少 name 属性,id 属性在发布 HTML 表单时毫无意义

    <input type="text" name="param1">
    

    【讨论】:

    • 添加名称属性允许我的数据到达 bean。另外,也不需要 EnableWebMvc。
    猜你喜欢
    • 2015-07-03
    • 2017-11-19
    • 1970-01-01
    • 2015-11-06
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多