Spring-Springboot控制器使用默认参数获取请求
我有一个带有两个GET端点的Springboot控制器:Spring-Springboot控制器使用默认参数获取请求,spring,spring-boot,kotlin,Spring,Spring Boot,Kotlin,我有一个带有两个GET端点的Springboot控制器: @RestController @RequestMapping("/foo") class MyController { fun getFoo( @RequestParam("x", required = false) x: Int = 0 ) = ... fun getFoo( @RequestParam("x", r
@RestController
@RequestMapping("/foo")
class MyController {
fun getFoo(
@RequestParam("x", required = false) x: Int = 0
) = ...
fun getFoo(
@RequestParam("x", required = true) x: Int,
@RequestParam("y", required = true) y: Int
) = ...
我想要的行为是,当被呼叫时:
使用可选的/foo
参数调用第一个端点x
使用提供的/foo?x=123
参数调用第一个端点x
x/foo?x=123&y=456'使用提供的
y`params调用第二个端点和
{
"timestamp": "2020-07-20T13:11:24.732+0000",
"status": 400,
"error": "Bad Request",
"message": "Parameter conditions \"x\" OR \"x, y\" not met for actual request parameters: ",
"path": "/foo"
}
您知道如何在指定零参数时确定默认端点吗?您可以在
@RequestParam
中将defaultValue
指定为String
:
fun getFoo(
@RequestParam(name = "x", required = false, defaultValue = "0") x: Int,
@RequestParam(name = "y", required = false, defaultValue = "1") y: Int
) =
Spring将使用与将
x
指定为参数(相同的强制、错误等)相同的方法将字符串
转换为您真正想要的任何类型(Int
),您可以在@RequestParam
中将默认值
指定为字符串
:
fun getFoo(
@RequestParam(name = "x", required = false, defaultValue = "0") x: Int,
@RequestParam(name = "y", required = false, defaultValue = "1") y: Int
) =
Spring将使用与指定x
作为参数(相同的强制、错误等)相同的方法将字符串
转换为您真正想要的任何类型(Int
),在@RequestMapping
或其变体(@GetMapping
,@PostMapping
等)中设置一个
例如
@GetMapping(params=arrayOf(“!x”,“!y”))
fun getFoo()
@GetMapping(参数=arrayOf(“x”,“!y”))
趣味格富(
@RequestParam(“x”,required=true)x:Int=0
@GetMapping(参数=arrayOf(“x”,“y”))
趣味格富(
@RequestParam(“x”,required=true)x:Int,
@RequestParam(“y”,required=true)y:Int
可以在同一URI上应用和标识不同的参数。在@RequestMapping
或其变体中设置一个参数(@GetMapping
,@PostMapping
等)
例如
@GetMapping(params=arrayOf(“!x”,“!y”))
fun getFoo()
@GetMapping(参数=arrayOf(“x”,“!y”))
趣味格富(
@RequestParam(“x”,required=true)x:Int=0
@GetMapping(参数=arrayOf(“x”,“y”))
趣味格富(
@RequestParam(“x”,required=true)x:Int,
@RequestParam(“y”,required=true)y:Int
可以在同一个URI上应用和标识不同的参数。如果您想要多个映射到同一url(很多时候这是一个代码气味,但有时是必要的,您可以在
@GetMapping
或@RequestMapping
注释的params元素中使用两个过滤参数
@RestController
@RequestMapping("/foo")
class MyController {
@GetMapping(params = ["!y"])
fun getFoo(
@RequestParam("x", required = false) x: Int?
) = ...
@GetMapping(params = ["x", "y"])
fun getFoo(
@RequestParam("x", required = true) x: Int,
@RequestParam("y", required = true) y: Int
) = ...
}
如果您想要多个映射到同一url(很多时候这是一个代码嗅,但有时是必要的),您可以在
@GetMapping
或@RequestMapping
annotations'params元素中使用两个过滤器参数
@RestController
@RequestMapping("/foo")
class MyController {
@GetMapping(params = ["!y"])
fun getFoo(
@RequestParam("x", required = false) x: Int?
) = ...
@GetMapping(params = ["x", "y"])
fun getFoo(
@RequestParam("x", required = true) x: Int,
@RequestParam("y", required = true) y: Int
) = ...
}