iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >SpringBoot与SpringMVC中参数传递的示例分析
  • 908
分享到

SpringBoot与SpringMVC中参数传递的示例分析

2023-06-20 17:06:14 908人浏览 独家记忆
摘要

小编给大家分享一下SpringBoot与springMVC中参数传递的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一:普通参数与基本注解HandlerM

小编给大家分享一下SpringBootspringMVC中参数传递的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

一:普通参数与基本注解

HandlerMapping中找到能处理请求的Handler(Controller,method())
为当前Handler找一个适配器HandlerAdapter:RequestMappingHandlerAdapter

SpringBoot与SpringMVC中参数传递的示例分析

HandlerAdapter

SpringBoot与SpringMVC中参数传递的示例分析

0-支持方法上标注@RequestMapping
1-支持函数式编程
xxxx

执行目标方法

SpringBoot与SpringMVC中参数传递的示例分析
SpringBoot与SpringMVC中参数传递的示例分析

参数解析器:确定要执行的目标方法每一个参数的值是什么

SpringBoot与SpringMVC中参数传递的示例分析

SpringBoot与SpringMVC中参数传递的示例分析

boolean supportsParameter(MethodParameter parameter);
Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
先判断是否支持该参数类型, 如果支持, 就调用resolveArgument解析方法

返回值处理器

SpringBoot与SpringMVC中参数传递的示例分析

挨个判断所有参数解析器哪个支持这个参数:HandlerMethodArgumentResolver: 把控着支持的方法参数类型

SpringBoot与SpringMVC中参数传递的示例分析

请求进来后, 首先从handlerMapping中查找是否有对应的映射处理, 得到映射适配器Adapter,再通过适配器,查找有哪些方法匹配请求,首先判断方法名,以及参数类型是否匹配,首先获得方法中声明的参数名字, 放到数组里,循环遍历27种解析器判断是否有支持处理对应参数名字类型的解析器,如果有的话,根据名字进行解析参数,根据名字获得域数据中的参数, 循环每个参数名字进行判断, 从而为每个参数进行赋值.

对于自定义的POJO类参数:
ServletRequestMethodArgumentResolver 这个解析器用来解析: 是通过主要是通过判断是否是简单类型得到的

@Overridepublic 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 instancetry {attribute = createAttribute(name, parameter, binderFactory, webRequest);}catch (BindException ex) {if (isBindExceptionRequired(parameter)) {// No BindingResult parameter -> fail with BindExceptionthrow ex;}// Otherwise, expose null/empty value and associated BindingResultif (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.Optionalif (!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 modelMap<String, Object> bindingResultModel = bindingResult.getModel();mavContainer.removeAttributes(bindingResultModel);mavContainer.addAllAttributes(bindingResultModel);return attribute;}

WebDataBinder binder =binderFactory.createBinder(webRequest,attribute,name)
WebDataBinder:web数据绑定器,将请求参数的值绑定到指定的javaBean里面
WebDataBinder 利用它里面的Converters将请求数据转成指定的数据类型,通过反射一系列操作,再次封装到javabean中

GenericConversionService:在设置每一个值的时候,找它里面所有的converter哪个可以将这个数据类型(request带来参数的字符串)转换到指定的类型(javabean—某一个类型)

SpringBoot与SpringMVC中参数传递的示例分析
SpringBoot与SpringMVC中参数传递的示例分析

未来我们可以给WebDataBinder里面放自己的Converter

private static final class StringToNumber implements Converter<String, T> {converter总接口:@FunctionalInterfacepublic interface Converter<S, T> {

//自定义转换器:实现按照自己的规则给相应对象赋值

@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;                }            });    }

二:复杂参数

Map/Model(map/model里面的数据会被放在request的请求域 相当于request.setAttribute)/Errors/BindingResult/RedirectAttributes(重定向携带数据)/ServletRespons().SessionStaus.UriComponentsBuilder

在上面第五步目标方法执行完成后:
将所有的数据都放在ModelAdnViewContainer;包含要去的页面地址View,还包含Model数据

SpringBoot与SpringMVC中参数传递的示例分析

处理派发结果

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

在页面进行响应前, 进行视图渲染的时候:
exposeModelAsRequestAttributes(model, request); 该方法将model中所有参数都放在请求域数据中

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);}}

通过循环遍历model中的所有数据放在请求域中

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集合或者Molde 最终在底层源码都是同一个对象在mvcContainer容器中进行保存

以上是“springBoot与SpringMVC中参数传递的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网精选频道!

--结束END--

本文标题: SpringBoot与SpringMVC中参数传递的示例分析

本文链接: https://www.lsjlt.com/news/298953.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • c语言怎么保证除完还是小数
    在 c 语言中,整数除法只能得到整数结果,要得到小数结果,需将操作数显式转换为浮点数:将一个操作数转换为浮点数,如 float result = num1 / (float)num2;将...
    99+
    2024-05-14
    c语言
  • c语言怎么让结尾不输出空行字符
    要阻止 c 语言程序结尾输出空行字符,可以使用以下方法:将 main 函数的返回值类型改为 void;在 main 函数中显式返回 0;调用 fflush(stdout) 函数刷新标准输...
    99+
    2024-05-14
    c语言
  • c语言怎么让结尾不输出空行数据
    在 c 语言中,可通过以下方法抑制 printf() 函数在程序结束时打印末尾空行:调用 fflush() 函数刷新缓冲区,立即输出所有数据;使用 setvbuf() 函数关闭缓冲,使数...
    99+
    2024-05-14
    c语言
  • c语言怎么让结尾无空行
    在 c 中去除结尾空行的方法:使用 fflush() 刷新缓冲区。使用 setvbuf() 将缓冲模式设置为 _ionbf。使用 printf 宏,它默认禁用缓冲。 如何在 C 语言中...
    99+
    2024-05-14
    c语言
  • c语言怎么输入实数赋值
    c语言中使用scanf()函数输入实数并赋值给变量:格式:scanf("%lf", &amp;variable);%lf是格式说明符,指定输入双精度浮点数;&...
    99+
    2024-05-14
    c语言
  • c语言怎么表达负数
    c语言中,负数以减号 (-) 表示,放在数字或变量前。负数运算规则包括:绝对值取正数;加正数或负数,结果取决于绝对值大小;乘或除以正数或负数,结果由符号奇偶性决定。负数的平方始终为正数,...
    99+
    2024-05-14
    c语言
  • c语言怎么输入Jac数列
    jacobi 数列的输入和生成方法分别有:1. 直接输入法:使用 scanf() 函数逐项输入数列。2. 递归生成法:使用递归公式生成数列,需初始化数列的前两项,然后按公式生成后续项。 ...
    99+
    2024-05-14
    c语言
  • c语言怎么把数组变成字符串
    在 c 语言中,将数组转换成字符串的方法包括:使用 sprintf() 将数组格式化为字符串。使用 strcpy() 将数组复制到字符串。使用 strncpy() 将指定长度的数组复制到...
    99+
    2024-05-14
    c语言
  • c语言怎么批量注释
    批量注释 c 语言代码的方法有:使用代码编辑器:使用快捷键或菜单命令自动添加 // 注释符号。使用注释工具:如 doxygen 和 cutter,批量添加行注释、块注释和文档注释。使用脚...
    99+
    2024-05-14
    python sublime c语言
  • c语言怎么把选中的全部注释
    c语言中注释选中内容可通过以下步骤实现:选中要注释的代码。根据使用的编辑器或ide,执行注释操作,例如在visual studio中右键单击并选择“注释所选内容”。添加注释内容。保存更改...
    99+
    2024-05-14
    sublime c语言
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作