這里使用反射來實現(xiàn)參數(shù)添加悼潭,先貼代碼再膳、Controller接口代碼:
@GetMapping("/test")
public Mono<String> test(String param1, String param2, String param3) {
return Mono.just(param1 + param2 + param3);
}
Filter代碼:
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class TokenFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// 獲取Request
ServerHttpResponse res = exchange.getResponse();
// 獲取參數(shù)列表
MultiValueMapAdapter params = (MultiValueMapAdapter) req.getQueryParams();
try {
// 反射獲取請求參數(shù)成員變量
Field targetMap = params.getClass().getDeclaredField("targetMap");
targetMap.setAccessible(true);
// 創(chuàng)建一個新的可修改的Map
Map newMap = new HashMap((Map) targetMap.get(params));
// TODO: 這里插入需要的參數(shù)(value類型需要是List)
newMap.put("param1", List.of("string1..."));
newMap.put("param2", List.of("string2..."));
newMap.put("param3", List.of("string3..."));
// 將原有參數(shù)表替換
targetMap.set(params, newMap);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return chain.filter(exchange);
}
}
效果:
插入?yún)?shù)可能需要注意的幾點:
1帚豪、請求參數(shù)列表QueryParams的類型是MultiValueMapAdapter粹排,參數(shù)存放在成員變量targetMap中
public class MultiValueMapAdapter<K, V> implements MultiValueMap<K, V>, Serializable {
private final Map<K, List<V>> targetMap;
// ...
}
2胁艰、targetMap是一個final成員,使用原有的put()进宝,add()等操作都會報下面這個錯
java.lang.UnsupportedOperationException
Caused by: java.lang.UnsupportedOperationException: null
at java.base/java.util.Collections$UnmodifiableMap.computeIfAbsent(Collections.java:1535)
at org.springframework.util.MultiValueMapAdapter.add(MultiValueMapAdapter.java:66)
// ...
3刻坊、targetMap的value需要是一個List,否則可能還會意外收獲這個錯
java.lang.ClassCastException: class java.lang.String cannot be cast to class java.util.List (java.lang.String and java.util.List are in module java.base of loader 'bootstrap')
at org.springframework.util.MultiValueMapAdapter.get(MultiValueMapAdapter.java:132)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ? springfox.boot.starter.autoconfigure.SwaggerUiWebFluxConfiguration$CustomWebFilter [DefaultWebFilterChain]
// ...