[英]Get request body as string/json to validate with a json schema- Spring boot REST API
I'm trying to validate JSON (passed by a client as a request body) before it is converted into a model in Controller method. 我正在尝试验证JSON(由客户端作为请求主体传递),然后再将其转换为Controller方法中的模型。
If validation passes then return nothing, let the process continue as it was (spring boot to convert JSON into a model marked as @RequestBody). 如果验证通过,则不返回任何内容,让该过程按原样继续(春季启动,将JSON转换为标记为@RequestBody的模型)。 Throw error in case validation fails ( everit-org/json-schema ). 万一验证失败则抛出错误( everit-org / json-schema )。
I tried to two way: 我尝试了两种方式:
Implement HandlerMethodArgumentResolver
, but resolveArgument()
doesn't give request body details as it is already read and stored in ContentCachingRequestWrapper
. 实现HandlerMethodArgumentResolver
,但resolveArgument()
不会提供请求正文详细信息,因为它已被读取并存储在ContentCachingRequestWrapper
。
NOTE: inputStream
in ContentCachingRequestWrapper
doesn't have any request body details. 注意: ContentCachingRequestWrapper
中的inputStream
没有任何请求正文详细信息。
Interceptor
. 使用弹簧 Interceptor
。 But this doesn't help me to find request body type passed in the request. 但这并不能帮助我找到在请求中传递的请求主体类型。 As JSON schema is different for each request. 由于JSON模式对于每个请求都是不同的。 Any other approaches I can try with? 我可以尝试其他方法吗?
I cannot add a comment ... so ... 我无法添加评论...所以...
What kind of validation do you need? 您需要哪种验证? If you only want to validate the fields like length of a string or range of a number and so on. 如果只想验证字段,例如字符串的长度或数字的范围等。 I recommend you use @Validated
on controller mehtod parameter, and model: 我建议您在控制器的@Validated
参数和模型上使用@Validated
:
@NotNull
@Size(min = 32, max = 32)
private String id;
controller: 控制器:
@PatchMapping
public Object update(@RequestBody @Validated User user, Errors errors) {
...
}
If there is something wrong, errors.hasErrors()
will return true
. 如果出现问题, errors.hasErrors()
将返回true
。
edit: 编辑:
OK, I did some tests, in a filter : 好的,我在过滤器中做了一些测试:
HttpServletRequest httpServletRequest = (HttpServletRequest)request;
ServletInputStream inputStream = httpServletRequest.getInputStream();
byte[] a = new byte[1024];
inputStream.read(a);
System.out.println(IOUtils.toString(a));
I got a json string (a piece of request body) : 我有一个json字符串(一个请求主体):
{"template":"5AF78355A4F0D58E03CE9F55AFA850F8","bd":"" ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.