自定义验证Spring请求参数

huangapple go评论60阅读模式
英文:

Custom validation of Spring request parameter

问题

我已经暴露了一个REST服务,它接受value_param作为请求参数。如果URL参数拼写不正确,将抛出以下异常:

白标签错误页面

此应用程序未对 /error 进行显式映射,因此您正在看到作为回退的内容。
2020年9月15日,上午10:57:54,印度标准时间
发生了意外错误(类型为Bad Request,状态为400)。
未提供所需的String参数 'value_param'

我正在尝试显式检查该参数。这个参数检查与其他检查结合在一起,如果任何验证检查失败,将抛出422错误。

以下是端点签名:

   @GetMapping("/values")
    public List<ValueEntity> getValues(@RequestParam(name = "value_param") String valueParameter) {

如何访问value_param参数并防止抛出状态为400的错误页面?

英文:

I've exposed a rest service that accepts value_param as a request parameter. If the url param is not spelt correctly then the following exception is thrown:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Sep 15 10:57:54 IST 2020
There was an unexpected error (type=Bad Request, status=400).
Required String parameter &#39;value_param&#39; is not present

I'm attempting to explicitly check the parameter. This parameter check is in combination with other checks and any validation check fails, throw a 422 error.

Here is the endpoint signature:

   @GetMapping(&quot;/values&quot;)
    public List&lt;ValueEntity&gt; getValues(@RequestParam(name = &quot;value_param&quot;) String valueParameter) {

How to access the value_param parameter and prevent the Error page with status 400 being thrown ?

答案1

得分: 1

将该字段标记为控制器中的 @RequestParam(required = false)。更详细的示例可以在这里查看:这里

英文:

Mark the field as @RequestParam(required = false) in the controller. <br>
For more detailed examples could be seen: here

huangapple
  • 本文由 发表于 2020年9月15日 18:29:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63899955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定