1. 程式人生 > >springboot重寫SpringMVC請求引數裝載

springboot重寫SpringMVC請求引數裝載

詳細原理解析參考恆宇少年: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.使用: