撸一个mvc框架

动手撸一个 mvc 框架5

2020-04-29  本文已影响0人  想54256

title: 动手撸一个 mvc 框架5
date: 2020/04/27 10:21


本节内容

  1. Init#afterPropertiesSet 初始化参数解析器、Binder的参数解析器、返回值解析器、@MA的缓存、@IB的缓存、ResponseBodyAdvice

ha.handlerInternal()

  1. checkAndPrepare(现在已废弃,不管)
  1. invokeHandlerMethod

前言

本节内容涉及到 @InitBinder、@ModelAttribute 和 @ControllerAdvice 注解,所以我们先介绍一下

@InitBinder 是参数绑定器,例如:

@InitBinder
protected void initBinder(WebDataBinder binder) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    simpleDateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, false));
}

如果用户请求时输入的是 String 类型的时间,而我们接收的是 Date 类型的,那么通过这个参数绑定器,Spring 就会自动帮我们把 String 类型的转换成 Date 类型的参数。

@ModelAttribute 比较复杂,我们举个例子来说明:

// 向 Model 中设置 {"className": cn.x5456.XXX}
@ModelAttribute("className")
public String setModel() {
    return this.getClass().getName();
}

// 向 Model 中设置 {"string": cn.x5456.XXX}
@ModelAttribute
public String setModel2() {
    return this.getClass().getName();
}

// 向 Model 中设置 {"className2": cn.x5456.XXX}
@ModelAttribute
public void setModel3(Model model) {
    model.addAttribute("className2", this.getClass().getName());
}

@ModelAttribute 就是为了在请求调用之前,让我们将一些参数放进 Model 中,例如:cookie 中用户登录的信息,我们只需要里面的角色,那么就不用每次 @CookieValue 获取 User 对象,然后再获取它的角色了。

@ControllerAdvice Advice 是“通知”的意思,顾名思义他和 AOP 有关,解释一下就是针对标注了 @Controller 注解的类的通知

它可以结合 @InitBinder 和 @ModelAttribute 注解一起使用,这样 @InitBinder 和 @ModelAttribute 注解的方法则针对所有的 Controller 都生效。

ResponseBodyAdvice 接口的实现类将在标注了 @ResponseBody 注解的方法返回之后进行调用,这样我们就可以对响应进行处理,它有 2 种注册方式 1. 直接注册到 RequestMappingHandlerAdapter 中,2. 直接给实现类添加 @ControllerAdvice 注解

Spring 4.0

我们先来看一个重点的 HandlerAdapter ,也就是 RequestMappingHandlerAdapter

它实现了 InitializingBean ,我们先来看看

image

请求来了

image image image

getDataBinderFactory() & getModelFactory()

image image

tag1

注:ModelFactory 的作用是在调用方法前对 Model 初始化,调用方法后更新 Model

向 Model 添加属性 image

tag2

image
tag4

在处理 @ModelAttribute 时也调用的这个方法(invokeModelAttributeMethods(request, mavContainer);)

image image image image

我们先看第 3 行

image

再看第 4 行

image

这个方法中从“类型注册中心”中找到合适的转换器,然后对其进行转换。

tag5
image image image image

tag3

image

自己实现

本部分设计到的组件太多,还是去 git 上下代码吧

上一篇 下一篇

猜你喜欢

热点阅读