Controller方法中单个id参数的空值检查

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

Null check for a single id parameter on the Controller method

问题

在Spring Boot控制器中,我正在尝试验证如下所示的Long类型的id字段:

@GetMapping("/{id}")
public ResponseEntity<EmployeeResponse> getById(@PathVariable @NotNull Long id) {
    final EmployeeResponse response = employeeService.getById(id);
    return ResponseEntity.ok(...);
}

但是当我尝试发送带有null id参数的请求时,我得到了以下错误:

"Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; For input string: ":id""

我还尝试使用long@Valid注解,但没有任何意义,遇到了类似的错误。所以,是否有可能验证请求的id参数?

英文:

In a Spring Boot Controller, I am trying to validate an id field in Long type as shown below:

@GetMapping(&quot;/{id}&quot;)
public ResponseEntity&lt;EmployeeResponse&gt; getById(@PathVariable @NotNull Long id) {
    final EmployeeResponse response = employeeService.getById(id);
    return ResponseEntity.ok(...);
}

But when I try to send request with null id parameter, ı get the following error:

> "Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; For input string: &quot;:id&quot;"

I also tried using long and @Valid annotation, but does not make any sense and a similar error is encountered. So, is it possible to validate id parameter of the request?

答案1

得分: 3

不确定将@PathVariable设置为@NotNull是否有意义?因为如果它为null,则URL会不同。因此,您可以使用其他端点@GetMapping("/")来处理。

英文:

Not sure if it make sense to have @PathVariable as @NotNull?
Because it's different url if it's null. So you could handle that with other endpoint @GetMapping("/")

答案2

得分: 0

另一种方法,我几乎总是在URL的路径和正常参数中使用的是:只需对每个参数使用String

由于URL可以被任何用户轻松操作,他们可以输入“.../sos”而不是有效的数字,你将收到相同的错误。

为什么呢?URL中的一切都是字符串。当Spring Boot注意到控制器接受一个Long作为参数时,它会尝试自行解析它。

如果你使用String,就不会发生这种情况,如前面提到的:URL中的一切都已经是字符串,SB不需要将其解析为任何其他数据类型。

我建议你也在方法中只使用String参数,然后通过.getById(Long.parseLong(id));手动进行解析/转换。

这样你可以捕获任何解析异常并返回适当的错误消息。

英文:

Another approach, which I pretty much always use for path & normal params in the URL, is the following: Just use String for every parameter.

As URL is easily manipulable by any user, they can e.g. just enter ".../sos" instead of a valid number and you'll receive the same error.

Why? Everything in a URL is a String. When Spring Boot notices the controller accepting a Long as a parameter, it tries to parse it by itself.

This won't happen if you use a String, as previously mentioned: everything in the URL already is a String and SB won't need to parse it to any other datatype.

I'd recommend you to just have String parameters in your method aswell and then just do the parsing/converting manually via .getById(Long.parseLong(id));.

This way you can e.g. catch any parse exception and return an appropriate error message.

答案3

得分: 0

你需要在 **@GetMapping** 中添加数值因为 URL 将等待带有数据的路径因为数据也意味着路径同时你需要添加 **@PathVariable(required = false)**这意味着在映射中你的地址不会等待数据如果你调用 ***&quot;/&quot;***它可以为 **null**在你的服务中你会看到 id 的数据是 **null**因为调用了路径的另一个值

    @GetMapping(value = {&quot;/{id}&quot;, &quot;&quot;})
    public ResponseEntity&lt;EmployeeResponse&gt; getById(@PathVariable(required = false) Long id) {
        if (id == null) { // 当为 null 时执行某些操作
            }
            else {// 执行另一种操作
            }
            返回 &quot;你的数据&quot;;
        }
英文:

You need to add values to @GetMapping, because URL will wait path with data, cuz data also means path. Also you need to add @PathVariable(required = false), it means your address in mapping will not wait data, and can come null if you ust call "/", in your service you see null data for id, cuz calls another value for your path.

@GetMapping(value = {&quot;/{id}&quot;, &quot;&quot;})
public ResponseEntity&lt;EmployeeResponse&gt; getById(@PathVariable(required = false) Long id) {
    if (id == null) { // Do something when null
        }
        else {// do another thing
        }
        return &quot;your data&quot;;
    }

答案4

得分: 0

如果您正在使用@PathVariable(...),它们不能是可选的。这反映了路径变量的本质 - 它们为空并不是一个合理的选择。REST风格的URL始终需要完整的URL路径。如果您有一个可选组件,考虑使用@RequestParam(...)

您可以在实体中使用@NotNull

英文:

If you are using

@PathVariable(...)

They cannot be optional. This reflects the nature of path variables - it doesn't really make sense for them to be null. REST-style URLs always need the full URL path. If you have an optional component, consider use

@RequestParam(...)

instead.

You can use
@NotNull
in your entities itself.

答案5

得分: -1

我建议您检查这个链接,特别是第六段,其中他解释了哪种类型的约束适用于哪种数据类型。

英文:

I suggest you check this
especially sixth paragraph, where he explains which sort of constraints work for which datatypes.

huangapple
  • 本文由 发表于 2023年3月3日 18:28:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625892.html
匿名

发表评论

匿名网友

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

确定