spring - 如何防止null RequestParam引发异常?

标签 spring model-view-controller kotlin null

我正在使用Kotlin在Spring Boot环境中工作。我用@GetMapping注释的方法制作了一个 Controller 。此方法有一些类型为@RequestParam的参数声明为Double类型。如果我尝试在不提供这些参数的情况下调用方法,则我的代码将引发以下异常:

java.lang.IllegalStateException: Optional double parameter 'latitude' is present but cannot be translated into a null value due to being declared as a primitive type.

我假设参数具有默认值(可能为0.0),但是Kotlin需要一个可以为null的对象,因此引发了异常。

如果我提供了参数,所有方法都可以正常工作,但是如果没有提供参数,我希望我的代码正常工作。

如何避免这种异常?

这是我的 Controller 的外观:
@RestController
@RequestMapping("/api/stations")
class StationController {

    @GetMapping
            fun findAll(@RequestParam(value = "latitude", required = false) currentLatitude: Double,
                        @RequestParam(value = "longitude", required = false) currentLongitude: Double): ResponseEntity<List<Entity>> {
                //Method body
            }

最佳答案

the documentation regarding basic types的以下部分可能会为您提供帮助:

On the Java platform, numbers are physically stored as JVM primitive types, unless we need a nullable number reference (e.g. Int?) or generics are involved. In the latter cases numbers are boxed.



那时您的猜测可能是正确的。尝试使用Double?,应该没问题。

关于spring - 如何防止null RequestParam引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54234325/

相关文章:

android - 如何在AppBarLayout Android中删除SearchView的查询文本中的下划线

java - 带有 MVC 的 Spring 3 JSON

java - Spring 端点为较大的 http 请求接收截断的正文

java - 带有复合主键的 Spring 数据

java - SYS.ODCIVARCHAR2LIST 的字段类型?

javascript - Aura 组件没有任何 DOM 元素?

iOS:应用程序中的模型架构

ruby-on-rails - 如果 Pundit 未授权显示操作,则重定向到特定 View

java - "error: cannot find symbol"在 flutter 中为 Android 构建时

android - RX如何根据错误类型返回Throwable或Object