详细原理解析参考恒宇少年:https://segmentfault.com/a/1190000011406515
本文只做将请求参数名转下划线的实现,数据装载的实现使用反射,让代码更为简练。
1.使用自定义注解:
/**
* 实体映射注解
* 配置该注解的参数会使用UnderlineToCamelArgumentResolver类完成装载
*/
@Target(value = ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ParameterModel {
}
2.实现HandlerMethodArgumentResolver接口:
/**
* 将请求参数带有下划线转驼峰命名
*/
public class UnderlineToCamelArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.hasParameterAnnotation(ParameterModel.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
return handleParameterNames(parameter, webRequest);
}
private Object handleParameterNames(MethodParameter parameter, NativeWebRequest webRequest) {
Object obj = BeanUtils.instantiate(parameter.getParameterType());
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(obj);
Iterator<String> paramNames = webRequest.getParameterNames();
while (paramNames.hasNext()) {
String paramName = paramNames.next();
Object o = webRequest.getParameter(paramName);
wrapper.setPropertyValue(underLineToCamel(paramName), o);
}
return obj;
}
private String underLineToCamel(String source) {
Matcher matcher = Pattern.compile("_(\\w)").matcher(source);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}
}
3.使用: