【问题标题】:Getting null in spring-boot REST request param from HTML form从 HTML 表单中获取 spring-boot REST 请求参数中的 null
【发布时间】:2020-04-03 14:08:51
【问题描述】:

我有一个 HTML 表单,我在其中获得 2 个输入,它被提交到 spring boot REST api。但在这个简单的应用程序中,我仍然在后端 api 中收到 null 作为请求。

表格

<div>
    <label>alphaID</label>  
    <div>
        <input id="alphaID" name="alphaID" type="text"/>
    </div>
</div>

<div>
    <label class="col-md-4 control-label">Domain Name</label>  
    <div class="col-md-4">
        <input id="domain" name="domain" type="text"/>
    </div>
</div>

提交后,我正在调用 ajax 调用,例如:

function formSubmit() {
    $("#productForm").submit(function(e) {
        e.preventDefault();
        var requestJson = createRequestJSON();
        var url = config.myurl;
        $.ajax({
            url: url,
            type : "POST",
            data: JSON.stringify(requestJson),
            success: function( data, textStatus, jQxhr ) {
                console.log("sucess: " + data);
            },
            error: function( jqXhr, textStatus, errorThrown ){
                console.log( "error: " + errorThrown );
            }
        });
    });
}

后端是一个带有 REST 调用的 spring-boot 应用程序:

@RequestMapping(value = "/validate", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Map<String, List<String>> validate(@Valid MyDTO myDTO) {

    System.out.println(myDTO.getId());          // GETTING null
    System.out.println(myDTO.getDomain());      // GETTING null

}

MyDTO.java

public class MyDTO {
    @JsonProperty("alpha_id")
    private String alphaID;

    @JsonProperty("domain")
    private String domain;

    ....
}

【问题讨论】:

    标签: javascript java jquery spring-boot


    【解决方案1】:

    看看你的requestJson 是否真的有正确的格式以便MyDTO 使用它可能会很有趣。

    您也不必Json.stringify您的数据。当你这样做时,你基本上只是向后端发送一个字符串。后端不知道它必须解析这个字符串才能得到一个有效的文档。您要么直接在 data 属性中发送 JavaScript 对象,要么将 API 更改为期望 String 并稍后在函数中解析它。

    【讨论】:

      【解决方案2】:

      将您的 Content-Type 更改为

      consumes = MediaType.APPLICATION_JSON_VALUE
      

      添加@RequestBody注解

      public Map<String, List<String>> validate(@Valid @RequestBody MyDTO myDTO)
      

      确保您调用正确的 URL 并从浏览器请求中发送正确的 content-type

      【讨论】:

      • 那么从浏览器,我应该发送application/json,对吧?
      • 我进行了更改,但出现错误:Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
      • 参考这篇文章在 Ajax 调用中添加 content-typeAccept 标头。 stackoverflow.com/questions/9754767/…
      猜你喜欢
      • 2022-11-18
      • 2019-11-01
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2017-03-11
      相关资源
      最近更新 更多