欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot與SpringMVC中參數(shù)傳遞的原理解析

 更新時間:2021年07月28日 10:47:51   作者:感謝一切給予  
這篇文章主要介紹了SpringBoot與SpringMVC中參數(shù)傳遞的原理,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一:普通參數(shù)與基本注解

HandlerMapping中找到能處理請求的Handler(Controller,method())
為當(dāng)前Handler找一個適配器HandlerAdapter:RequestMappingHandlerAdapter

在這里插入圖片描述

1.HandlerAdapter

在這里插入圖片描述

0-支持方法上標(biāo)注@RequestMapping
1-支持函數(shù)式編程的
xxxx

2.執(zhí)行目標(biāo)方法

在這里插入圖片描述
在這里插入圖片描述

3.參數(shù)解析器:確定要執(zhí)行的目標(biāo)方法每一個參數(shù)的值是什么

在這里插入圖片描述

在這里插入圖片描述

boolean supportsParameter(MethodParameter parameter);
Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
先判斷是否支持該參數(shù)類型, 如果支持, 就調(diào)用resolveArgument解析方法

4.返回值處理器

在這里插入圖片描述

5.挨個判斷所有參數(shù)解析器哪個支持這個參數(shù):HandlerMethodArgumentResolver: 把控著支持的方法參數(shù)類型

在這里插入圖片描述

請求進(jìn)來后, 首先從handlerMapping中查找是否有對應(yīng)的映射處理, 得到映射適配器Adapter,再通過適配器,查找有哪些方法匹配請求,首先判斷方法名,以及參數(shù)類型是否匹配,首先獲得方法中聲明的參數(shù)名字, 放到數(shù)組里,循環(huán)遍歷27種解析器判斷是否有支持處理對應(yīng)參數(shù)名字類型的解析器,如果有的話,根據(jù)名字進(jìn)行解析參數(shù),根據(jù)名字獲得域數(shù)據(jù)中的參數(shù), 循環(huán)每個參數(shù)名字進(jìn)行判斷, 從而為每個參數(shù)進(jìn)行賦值.

對于自定義的POJO類參數(shù):
ServletRequestMethodArgumentResolver 這個解析器用來解析: 是通過主要是通過判斷是否是簡單類型得到的

@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return (parameter.hasParameterAnnotation(ModelAttribute.class) ||
				(this.annotationNotRequired && !BeanUtils.isSimpleProperty(parameter.getParameterType())));
	}
	
public static boolean isSimpleValueType(Class<?> type) {
		return (Void.class != type && void.class != type &&
				(ClassUtils.isPrimitiveOrWrapper(type) ||
				Enum.class.isAssignableFrom(type) ||
				CharSequence.class.isAssignableFrom(type) ||
				Number.class.isAssignableFrom(type) ||
				Date.class.isAssignableFrom(type) ||
				Temporal.class.isAssignableFrom(type) ||
				URI.class == type ||
				URL.class == type ||
				Locale.class == type ||
				Class.class == type));
	}


public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

		Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer");
		Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory");

		String name = ModelFactory.getNameForParameter(parameter);
		ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
		if (ann != null) {
			mavContainer.setBinding(name, ann.binding());
		}

		Object attribute = null;
		BindingResult bindingResult = null;

		if (mavContainer.containsAttribute(name)) {
			attribute = mavContainer.getModel().get(name);
		}
		else {
			// Create attribute instance
			try {
				attribute = createAttribute(name, parameter, binderFactory, webRequest);
			}
			catch (BindException ex) {
				if (isBindExceptionRequired(parameter)) {
					// No BindingResult parameter -> fail with BindException
					throw ex;
				}
				// Otherwise, expose null/empty value and associated BindingResult
				if (parameter.getParameterType() == Optional.class) {
					attribute = Optional.empty();
				}
				else {
					attribute = ex.getTarget();
				}
				bindingResult = ex.getBindingResult();
			}
		}

		if (bindingResult == null) {
			// Bean property binding and validation;
			// skipped in case of binding failure on construction.
			WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
			if (binder.getTarget() != null) {
				if (!mavContainer.isBindingDisabled(name)) {
					bindRequestParameters(binder, webRequest);
				}
				validateIfApplicable(binder, parameter);
				if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
					throw new BindException(binder.getBindingResult());
				}
			}
			// Value type adaptation, also covering java.util.Optional
			if (!parameter.getParameterType().isInstance(attribute)) {
				attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
			}
			bindingResult = binder.getBindingResult();
		}

		// Add resolved attribute and BindingResult at the end of the model
		Map<String, Object> bindingResultModel = bindingResult.getModel();
		mavContainer.removeAttributes(bindingResultModel);
		mavContainer.addAllAttributes(bindingResultModel);

		return attribute;
	}

WebDataBinder binder =binderFactory.createBinder(webRequest,attribute,name)
WebDataBinder:web數(shù)據(jù)綁定器,將請求參數(shù)的值綁定到指定的javaBean里面
WebDataBinder 利用它里面的Converters將請求數(shù)據(jù)轉(zhuǎn)成指定的數(shù)據(jù)類型,通過反射一系列操作,再次封裝到j(luò)avabean中

GenericConversionService:在設(shè)置每一個值的時候,找它里面所有的converter哪個可以將這個數(shù)據(jù)類型(request帶來參數(shù)的字符串)轉(zhuǎn)換到指定的類型(javabean—某一個類型)

在這里插入圖片描述
在這里插入圖片描述

未來我們可以給WebDataBinder里面放自己的Converter

private static final class StringToNumber implements Converter<String, T> {

converter總接口:
@FunctionalInterface
public interface Converter<S, T> {

//自定義轉(zhuǎn)換器:實現(xiàn)按照自己的規(guī)則給相應(yīng)對象賦值

@Override
    public void addFormatters(FormatterRegistry registry) {
            registry.addConverter(new Converter<String, Pet>() {
                @Override
                public Pet convert(String source) {
                    if (!StringUtils.isEmpty(source)){
                        Pet pet = new Pet();
                        String[] split = source.split(",");
                        pet.setName(split[0]);
                        pet.setAge(split[1]);
                        return pet;
                    }

                    return null;
                }
            });
    }

二:復(fù)雜參數(shù)

Map/Model(map/model里面的數(shù)據(jù)會被放在request的請求域 相當(dāng)于request.setAttribute)/Errors/BindingResult/RedirectAttributes(重定向攜帶數(shù)據(jù))/ServletRespons().SessionStaus.UriComponentsBuilder

6.在上面第五步目標(biāo)方法執(zhí)行完成后:
將所有的數(shù)據(jù)都放在ModelAdnViewContainer;包含要去的頁面地址View,還包含Model數(shù)據(jù)

在這里插入圖片描述

7.處理派發(fā)結(jié)果

processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);

在頁面進(jìn)行響應(yīng)前, 進(jìn)行視圖渲染的時候:
exposeModelAsRequestAttributes(model, request); 該方法將model中所有參數(shù)都放在請求域數(shù)據(jù)中

protected void renderMergedOutputModel(
			Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

		// Expose the model object as request attributes.
		exposeModelAsRequestAttributes(model, request);

		// Expose helpers as request attributes, if any.
		exposeHelpers(request);

		// Determine the path for the request dispatcher.
		String dispatcherPath = prepareForRendering(request, response);

		// Obtain a RequestDispatcher for the target resource (typically a JSP).
		RequestDispatcher rd = getRequestDispatcher(request, dispatcherPath);
		if (rd == null) {
			throw new ServletException("Could not get RequestDispatcher for [" + getUrl() +
					"]: Check that the corresponding file exists within your web application archive!");
		}

		// If already included or response already committed, perform include, else forward.
		if (useInclude(request, response)) {
			response.setContentType(getContentType());
			if (logger.isDebugEnabled()) {
				logger.debug("Including [" + getUrl() + "]");
			}
			rd.include(request, response);
		}

		else {
			// Note: The forwarded resource is supposed to determine the content type itself.
			if (logger.isDebugEnabled()) {
				logger.debug("Forwarding to [" + getUrl() + "]");
			}
			rd.forward(request, response);
		}
	}

通過循環(huán)遍歷model中的所有數(shù)據(jù)放在請求域中

protected void exposeModelAsRequestAttributes(Map<String, Object> model,
			HttpServletRequest request) throws Exception {
		
		model.forEach((name, value) -> {
			if (value != null) {
				request.setAttribute(name, value);
			}
			else {
				request.removeAttribute(name);
			}
		});
	}

不管我們在方法形參位置放 Map集合或者M(jìn)olde 最終在底層源碼都是同一個對象在mvcContainer容器中進(jìn)行保存

到此這篇關(guān)于SpringBoot與SpringMVC中參數(shù)傳遞的原理的文章就介紹到這了,更多相關(guān)SpringBoot SpringMVC參數(shù)傳遞內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論