简体   繁体   English

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

[英]@RequestBody not parsing request into object for validation

I'm fairly new to Java/Spring and trying to set up an API Endpoint in an existing project. 我是Java / Spring的新手,正在尝试在现有项目中设置API端点。 I've essentially copied some of the other endpoints that are currently working, but mine is not validating when being hit and it seems to be because the @RequestBody is not populating the object being fed into the method. 我本质上已经复制了一些其他当前正在工作的端点,但是我的对象在被命中时未进行验证,这似乎是因为@RequestBody没有填充要馈入该方法的对象。

I've tried removing @NotNull but it's still failing out. 我试过删除@NotNull但仍失败。 This seems odd given that other endpoints are working w/the @NotNull . 鉴于其他端点正在使用@NotNull进行工作,这似乎很奇怪。

SampleRequest.java 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 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 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 test.py


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

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

When I run test.py I expect it to return appropriately, however instead I get a validation error because sample is null from SampleRequestResource.java 当我运行test.py我希望它能正确返回,但是相反,我收到了验证错误,因为SampleRequestResource.java samplenull

I'm assuming the @RequestBody should parse the request and when it calls the SampleRequestResource it will push the parsed request to SampleRequest and validate just fine, as this is what seems to be happening in the rest of the API (like I said, I directly copied/altered other working endpoints to create mine.) 我假设@RequestBody应该解析请求,当它调用SampleRequestResource ,它将把解析后的请求推送到SampleRequest并验证就好了,因为这似乎在其余的API中发生了(就像我说的,直接复制/更改其他工作端点以创建我的端点。)

according to your request object, json request should look like below 根据您的请求对象,json请求应如下所示

{
  "sample":{
             "testString":"foo"
           }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM