我正在使用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/