@RequestParam
是最简单的方法,它允许您定义查询参数的确切名称,例如:
@PostMapping
public String foo(@RequestParam("player_id") String playerId){
}
如果要将所有查询参数绑定到一个对象,则必须使用@ModelAttribute
. 它基于DataBinder
杰克逊,与杰克逊无关。默认情况下,它只支持将查询参数绑定到字段与查询参数同名的对象。因此,您可以考虑将查询参数绑定到以下对象:
public class Request {
private String player_id;
private String product_id;
private Long total_amount;
}
如果您真的想从具有蛇大小写值的查询参数绑定到遵循传统 java 命名约定(即小驼峰大小写)的对象,则必须自定义WebDataBinder
。
这个想法是覆盖它addBindValues()
并检查查询参数名称是否为蛇形格式,将其转换为小驼峰格式,并将其添加为请求的绑定值。就像是 :
public class MyServletRequestDataBinder extends ExtendedServletRequestDataBinder {
private static Converter<String, String> snakeCaseToLowerCamelConverter = CaseFormat.LOWER_UNDERSCORE
.converterTo(CaseFormat.LOWER_CAMEL);
public MyServletRequestDataBinder(Object target) {
super(target);
}
public MyServletRequestDataBinder(Object target, String objectName) {
super(target, objectName);
}
@Override
protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) {
super.addBindValues(mpvs, request);
Enumeration<String> paramNames = request.getParameterNames();
while (paramNames != null && paramNames.hasMoreElements()) {
String paramName = paramNames.nextElement();
if(paramName.contains("_")) {
String[] values = request.getParameterValues(paramName);
if (values == null || values.length == 0) {
// Do nothing, no values found at all.
} else if (values.length > 1) {
mpvs.addPropertyValue(snakeCaseToLowerCamelConverter.convert(paramName), values);
} else {
mpvs.addPropertyValue(snakeCaseToLowerCamelConverter.convert(paramName), values[0]);
}
}
}
}
}
PS 我正在使用 Guava 帮助我将蛇盒转换为 lowerCamelCase。
但是为了使用定制的WebDataBinder
,你必须反过来定制WebDataBinderFactory
, RequestMappingHandlerAdapter
因为:
- 定制
WebDataBinderFactory
以创建定制的WebDataBinder
- 自定义
RequestMappingHandlerAdapter
以创建WebDataBinderFactory
就像是:
public class MyServletRequestDataBinderFactory extends ServletRequestDataBinderFactory {
public MyServletRequestDataBinderFactory(List<InvocableHandlerMethod> binderMethods,
WebBindingInitializer initializer) {
super(binderMethods, initializer);
}
@Override
protected ServletRequestDataBinder createBinderInstance(Object target, String objectName,
NativeWebRequest request) throws Exception {
return new MyServletRequestDataBinder(target, objectName);
}
}
和
public class MyRequestMappingHandlerAdapter extends RequestMappingHandlerAdapter {
@Override
protected InitBinderDataBinderFactory createDataBinderFactory(List<InvocableHandlerMethod> binderMethods)
throws Exception {
return new MyServletRequestDataBinderFactory(binderMethods, getWebBindingInitializer());
}
}
最后注册以RequestMappingHandlerAdapter
在您的配置中使用自定义:
@Configuration
public class Config extends DelegatingWebMvcConfiguration {
@Override
protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {
return new MyRequestMappingHandlerAdapter();
}
}