Spring WebFlux 中, request.queryParams 只能获取到 查询参数, 对于 form 提交的参数无法进行参数自动装载
处理方式有两种:
ArgumentResolver
, 具体如下:org.springframework.web.reactive.config.WebFluxConfigurer
configureArgumentResolvers
, 自定义 ArgumentResolver
ServerWebExchange.formData
中查找参数值返回@Configuration
class WebConfig : WebFluxConfigurer {
@Autowired
private lateinit var applicationContext: ConfigurableApplicationContext
override fun configureArgumentResolvers(configurer: ArgumentResolverConfigurer) {
class RequestFormDataMethodArgumentResolver(
beanFactory: ConfigurableBeanFactory,
registry: ReactiveAdapterRegistry,
useDefaultResolution: Boolean
): RequestParamMethodArgumentResolver(beanFactory, registry, useDefaultResolution) {
override fun resolveNamedValue(name: String, parameter: MethodParameter, exchange: ServerWebExchange): Any? {
var result: Any? = null
val formData = exchange.formData.block()
val values = formData[name]
if( null != values ){
result = values.takeUnless { it.size == 1 } ?: values[0]
}
return result
}
}
configurer.addCustomResolver(RequestFormDataMethodArgumentResolver(applicationContext.beanFactory, ReactiveAdapterRegistry.getSharedInstance(), true))
}
}
该方法无法绑定 @RequestParam
标记的参数
查看org.springframework.web.reactive.result.method.annotation.ControllerResolver
我们的自定义参数处理器是位于列表末尾的, 对于 @RequestParam
标记的参数已经有前面的处理器处理过了
例如:
@PostMapping
fun create(name: String, password: String) { ... }
可以改成为:
@PostMapping
fun create(user: User) {println("$user.name - $user.password") }
作为对象封装将会触发spring的databinder机制
WebFlux 中实现了org.springframework.web.bind.support.WebExchangeDataBinder
在检测到不是基本参数的时候, 需要进行参数绑定动作
/**
* Combine query params and form data for multipart form data from the body
* of the request into a {@code Map} of values to use for
* data binding purposes.
* @param exchange the current exchange
* @return a {@code Mono} with the values to bind
* @see org.springframework.http.server.reactive.ServerHttpRequest#getQueryParams()
* @see ServerWebExchange#getFormData()
* @see ServerWebExchange#getMultipartData()
*/
public static Mono
这里可以看见, 进行参数绑定是从 queryParams, formData, multipartData 三个地方读取, 所以, 对象中的参数是可以正常绑定的
WebFlux 官方文档中提到, formdata数据来自于 application/x-www-form-urlencoded
, 所以使用以上方式实现 form data 参数绑定的, 注意了, 提交方式一定为: application/x-www-form-urlencoded
, 否则, 请使用 request body