spring boot 사용자 정의 매개 변수 해석 기 구현 form 폼 형식 요청 또는 주소 표시 줄 요청 매개 변수 밑줄 회전 낙타 봉 속성

5850 단어 springboot
1. 매개 변수 해석 설명 정의
@Target(value = ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ParameterModel {
}

2. 추상 류 AbstractCustomizeResolver 계승 HandlerMethodArgument Resolver 정의
public abstract class AbstractCustomizeResolver implements HandlerMethodArgumentResolver {
	//  
	protected void valid(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory, Object arg) throws Exception {
		String name = Conventions.getVariableNameForParameter(parameter);
		WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
		if (arg != null) {
			validateIfApplicable(binder, parameter);
			if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
				throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
			}
		}
		mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
	}

	/**
	 * Validate the binding target if applicable.
	 * 

The default implementation checks for {@code @javax.validation.Valid}, * Spring's {@link Validated}, * and custom annotations whose name starts with "Valid". * @param binder the DataBinder to be used * @param parameter the method parameter descriptor * @since 4.1.5 * @see #isBindExceptionRequired */ protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) { Annotation[] annotations = parameter.getParameterAnnotations(); for (Annotation ann : annotations) { Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class); if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) { Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann)); Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[]{hints}); binder.validate(validationHints); break; } } } protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter parameter) { int i = parameter.getParameterIndex(); Class>[] paramTypes = parameter.getMethod().getParameterTypes(); boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1])); return !hasBindingResult; } }


3. 정의 UnderlineToCamelArgument Resolver 계승 AbstractCustomizeResolver
public class UnderlineToCamelArgumentResolver extends AbstractCustomizeResolver {


	/**
	 * Whether the given {@linkplain MethodParameter method parameter} is
	 * supported by this resolver.
	 * @param parameter the method parameter to check
	 * @return {@code true} if this resolver supports the supplied parameter;
	 * {@code false} otherwise
	 */
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(ParameterModel.class);
	}

	/**
	 *     
	 *
	 * @param methodParameter           
	 * @param modelAndViewContainer       
	 * @param nativeWebRequest            
	 * @param webDataBinderFactory        
	 * @return the resolved argument value, or {@code null}
	 * @throws Exception in case of errors with the preparation of argument values
	 */
	@Override
	public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
		Object org=handleParameterNames(methodParameter, nativeWebRequest);
		valid(methodParameter,modelAndViewContainer,nativeWebRequest,webDataBinderFactory,org);
		return org;
	}

	//    
	private Object handleParameterNames(MethodParameter parameter, NativeWebRequest webRequest) {
		Object obj = BeanUtils.instantiate(parameter.getParameterType());
		BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(obj);
		Iterator paramNames = webRequest.getParameterNames();
		while (paramNames.hasNext()) {
			String paramName = paramNames.next();
			Object o = webRequest.getParameter(paramName);
			wrapper.setPropertyValue(StringHelpers.underLineToCamel(paramName), o);
		}
		return obj;
	}
}

4, 정의 도구 클래스 StringHelpers 처리 낙타 봉 과 밑줄 의 교환
public class StringHelpers {
	/**
	 *   _       
	 */
	private static final Pattern UNDER_LINE_PATTERN = Pattern.compile("_(\\w)");


	/***
	 *            
	 *
	 * @param source
	 *                 
	 */

	public static String underlineToHump(String source) {
		StringBuffer result = new StringBuffer();
		String a[] = source.split("_");
		for (String s : a) {
			if (result.length() == 0) {
				result.append(s.toLowerCase());
			} else {
				result.append(s.substring(0, 1).toUpperCase());
				result.append(s.substring(1).toLowerCase());
			}
		}
		return result.toString();
	}


	/***
	 *            
	 *
	 * @param source
	 *                
	 */

	public static String humpToUnderline(String source) {
		StringBuffer sb = new StringBuffer(source);
		int temp = 0;//  
		for (int i = 0; i < source.length(); i++) {
			if (Character.isUpperCase(source.charAt(i))) {
				sb.insert(i + temp, "_");
				temp += 1;
			}
		}
		return sb.toString().toUpperCase();
	}

	/**
	 * Create by lrt
* Date:2018/10/10 * Description: * * @param source * @return java.lang.String */ public static String underLineToCamel(String source) { // Pattern matcher() Matcher Matcher matcher = UNDER_LINE_PATTERN.matcher(source); StringBuffer result = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(result, matcher.group(1).toUpperCase()); } matcher.appendTail(result); return result.toString(); } }

좋은 웹페이지 즐겨찾기