DispatcherServlet之解析controller方法參數上的註解

注:SpringFramework的版本是4.3.x。java

    建議先看個人另外一篇文章,以後再來看這篇。web

                

                             圖1 ServletHandlerMethodInvoker的invokeHandlerMethod方法時序圖cookie

  1.     將HttpServletRequest中的請求參數轉換爲Controller類方法上實體類的操做,在步驟3的方法中。
  2.     步驟3的方法resolveHandlerArguments中,首先會取得方法上定義的全部參數類型,做爲外層for循環,而後單獨對每個參數再進行分析,Java語法中每一個參數是能夠定義多個註解的。

    下面給出方法resolveHandlerArguments部分源碼片斷,以下List-1所示,方法中代碼較多,建議讀者看源碼。ui

    List-1 方法resolveHandlerArguments部分源碼this

private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
		NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception {
	Class<?>[] paramTypes = handlerMethod.getParameterTypes();
	Object[] args = new Object[paramTypes.length];

	for (int i = 0; i < args.length; i++) {
		MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i);
		methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);
		GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());
		String paramName = null;
		String headerName = null;
		boolean requestBodyFound = false;
		String cookieName = null;
		String pathVarName = null;
		String attrName = null;
		boolean required = false;
		String defaultValue = null;
		boolean validate = false;
		Object[] validationHints = null;
		int annotationsFound = 0;
		Annotation[] paramAnns = methodParam.getParameterAnnotations();

		for (Annotation paramAnn : paramAnns) {
			if (RequestParam.class.isInstance(paramAnn)) {
				RequestParam requestParam = (RequestParam) paramAnn;
				paramName = requestParam.name();
				required = requestParam.required();
				defaultValue = parseDefaultValueAttribute(requestParam.defaultValue());
				annotationsFound++;
			}
			else if (RequestHeader.class.isInstance(paramAnn)) {
				RequestHeader requestHeader = (RequestHeader) paramAnn;
				headerName = requestHeader.name();
				required = requestHeader.required();
				defaultValue = parseDefaultValueAttribute(requestHeader.defaultValue());
				annotationsFound++;
			}
			else if (RequestBody.class.isInstance(paramAnn)) {
				requestBodyFound = true;
				annotationsFound++;
			}
			else if (CookieValue.class.isInstance(paramAnn)) {
				CookieValue cookieValue = (CookieValue) paramAnn;
				cookieName = cookieValue.name();
				required = cookieValue.required();
				defaultValue = parseDefaultValueAttribute(cookieValue.defaultValue());
				annotationsFound++;
			}
......

    這裏就是將HttpServletRequest請求數據轉換爲controller方法參數的入口了,後面就再也不細講,若是想了解某個特定的註解,從這裏着手分析就能夠了。.net

相關文章
相關標籤/搜索