@RequestBody未将请求解析为对象以进行验证

时间:2019-07-03 13:09:51

标签: java spring spring-mvc

我是Java / Spring的新手,正在尝试在现有项目中设置API端点。我实质上已经复制了一些其他当前正在工作的端点,但是我的端点在被命中时并未进行验证,这似乎是因为@RequestBody没有填充要馈入该方法的对象。

我尝试删除@NotNull,但仍然失败。鉴于其他端点正在使用@NotNull,这似乎很奇怪。

SampleRequest.java

import NotNull;

public class SampleRequest {

    @NotNull
    private String testString;

    public void setTestString(String testString):
        this.testString = testString;

    public String getTestString():
        return testString;
}

SampleRequestResource.java

import Valid
import NotNull

public class SampleRequestResource {

    @NotNull;
    @Valid;
    private SampleRequest sample;

    public SampleRequest getSample():
        return sample;

    public void setSampleRequest(SampleRequest sample):
        this.sample = sample;
}

SampleController.java

import RequestBody
import RequestMapping
import RestController

@RestController
@RequestMapping("/foo")
public class SampleController(){

    @RequestMapping("/{id}/bar", method = request.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<SampleResponseResource> stuff(
        @Valid @RequestBody SampleRequestResource request) {
            do stuff;
        return response;        
        })
}

test.py


import requests, json
header = {"Content-Type":"application/json"}
data = {"testString": "foo"}

test = requests.post(url, header=header, json=data, verify=false)

运行test.py时,我希望它能正确返回,但是相反,我收到验证错误,因为sample中的nullSampleRequestResource.java

我假设@RequestBody应该解析请求,并且当它调用SampleRequestResource时,它将把解析后的请求推送到SampleRequest并验证就好了,因为这似乎是会在其余的API中发生(就像我说的那样,我直接复制/更改了其他工作端点来创建我的地雷。)

1 个答案:

答案 0 :(得分:4)

根据您的请求对象,json请求应如下所示

connectionString="data source=SERVER\INSTANCE;
   Initial Catalog=MyDB;Integrated Security=True;"