欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解SpringBoot中添加@ResponseBody注解会发生什么

程序员文章站 2022-03-21 11:38:25
springboot版本2.2.4.release。【1】springboot接收到请求① springboot接收到一个请求返回json格式的列表,方法参数为jsonobject 格式,使用了注解@...

springboot版本2.2.4.release。

【1】springboot接收到请求

① springboot接收到一个请求返回json格式的列表,方法参数为jsonobject 格式,使用了注解@requestbody

为什么这里要说明返回格式、方法参数、参数注解?因为方法参数与参数注解会影响你使用不同的参数解析器与后置处理器!通常使用webdatabinder进行参数数据绑定结果也不同。

将要调用的目标方法如下:

  @apioperation(value="分页查询")
  @requestmapping(value = "/listpage",method = requestmethod.post)
  @responsebody
  public responsebean listpage(@requestbody jsonobject params){
    integer pagenum = params.getinteger("pagenum");
    integer pagesize = params.getinteger("pagesize");
    string vagueparam = params.getstring("vagueparam");
    ipage<tbsysgoodscategory> indexpage = new page<>(pagenum, pagesize);
    querywrapper<tbsysgoodscategory> querywrapper = new querywrapper<>();
    if (!stringutils.isempty(vagueparam)){
      querywrapper.like("name",vagueparam).or().like("code",vagueparam);
    }
    //排序
    querywrapper.orderbydesc("id");
    indexpage = tbsysgoodscategoryservice.page(indexpage,querywrapper);
    return new responsebean<>(true, indexpage, commonenum.success_option);
  }

如下所示,首先进入dispatcherservlet使用requestmappinghandleradapter进行处理。

详解SpringBoot中添加@ResponseBody注解会发生什么

而requestmappinghandleradapter (extends abstracthandlermethodadapter)会调用父类abstracthandlermethodadapter的handle方法进行处理。

abstracthandlermethodadapter.handle方法源码如下:

@override
@nullable
public final modelandview handle(httpservletrequest request, httpservletresponse response, object handler)
		throws exception {

	return handleinternal(request, response, (handlermethod) handler);
}

详解SpringBoot中添加@ResponseBody注解会发生什么

可以看到requestmappinghandleradapter还实现了initializingbean接口,该接口只有一个抽象方法afterpropertiesset用于在beanfactory设置完bean属性后执行,具体可参考博文:spring - bean的初始化和销毁几种实现方式详解

② requestmappinghandleradapter.handleinternal

这里首先在this.checkrequest(request)对请求进行了检测,httprequestmethodnotsupportedexception异常就是这里抛出的。

//1.检测请求方法是否支持;
//2.检测是否需要session但是没有获取到
	protected final void checkrequest(httpservletrequest request) throws servletexception {
		// check whether we should support the request method.
		string method = request.getmethod();
		if (this.supportedmethods != null && !this.supportedmethods.contains(method)) {
			throw new httprequestmethodnotsupportedexception(method, this.supportedmethods);
		}

		// check whether a session is required.
		if (this.requiresession && request.getsession(false) == null) {
			throw new httpsessionrequiredexception("pre-existing session required but none found");
		}
	}

其他没有什么需要特殊说明的,然后直接调用了invokehandlermethod方法进行实际业务处理。

详解SpringBoot中添加@ResponseBody注解会发生什么

【2】requestmappinghandleradapter.invokehandlermethod核心处理

requestmappinghandleradapter.invokehandlermethod

这个方法十分重要,是请求处理流程中的核心方法。这个方法会根据handlermethod获取一个servletinvocablehandlermethod 并对其进行各种属性设置然后调用其invokeandhandle方法进行处理。

 @nullable
  protected modelandview invokehandlermethod(httpservletrequest request, httpservletresponse response, handlermethod handlermethod) throws exception {
  // 对应 2 
    servletwebrequest webrequest = new servletwebrequest(request, response);

    object result;
    try {
// 对应 3
      webdatabinderfactory binderfactory = this.getdatabinderfactory(handlermethod);
  // 对应 4
      modelfactory modelfactory = this.getmodelfactory(handlermethod, binderfactory);
  // 对应 5
      servletinvocablehandlermethod invocablemethod = this.createinvocablehandlermethod(handlermethod);
      if (this.argumentresolvers != null) {
        invocablemethod.sethandlermethodargumentresolvers(this.argumentresolvers);
      }

      if (this.returnvaluehandlers != null) {
        invocablemethod.sethandlermethodreturnvaluehandlers(this.returnvaluehandlers);
      }

      invocablemethod.setdatabinderfactory(binderfactory);
      invocablemethod.setparameternamediscoverer(this.parameternamediscoverer);
 // 对应 6
      modelandviewcontainer mavcontainer = new modelandviewcontainer();
      mavcontainer.addallattributes(requestcontextutils.getinputflashmap(request));
      modelfactory.initmodel(webrequest, mavcontainer, invocablemethod);
      mavcontainer.setignoredefaultmodelonredirect(this.ignoredefaultmodelonredirect);
//对应 7
      asyncwebrequest asyncwebrequest = webasyncutils.createasyncwebrequest(request, response);
      asyncwebrequest.settimeout(this.asyncrequesttimeout);
      webasyncmanager asyncmanager = webasyncutils.getasyncmanager(request);
      asyncmanager.settaskexecutor(this.taskexecutor);
      asyncmanager.setasyncwebrequest(asyncwebrequest);
      asyncmanager.registercallableinterceptors(this.callableinterceptors);
      asyncmanager.registerdeferredresultinterceptors(this.deferredresultinterceptors);
      if (asyncmanager.hasconcurrentresult()) {
        result = asyncmanager.getconcurrentresult();
        mavcontainer = (modelandviewcontainer)asyncmanager.getconcurrentresultcontext()[0];
        asyncmanager.clearconcurrentresult();
        logformatutils.tracedebug(this.logger, (traceon) -> {
          string formatted = logformatutils.formatvalue(result, !traceon);
          return "resume with async result [" + formatted + "]";
        });
        invocablemethod = invocablemethod.wrapconcurrentresult(result);
      }
//这里会跳到【3】servletinvocablehandlermethod.invokeandhandle
      invocablemethod.invokeandhandle(webrequest, mavcontainer, new object[0]);
      
      if (!asyncmanager.isconcurrenthandlingstarted()) {
//这里会跳到【4】requestmappinghandleradapter.getmodelandview
        modelandview var15 = this.getmodelandview(mavcontainer, modelfactory, webrequest);
        return var15;
      }

      result = null;
    } finally {
    //这里会跳到【5】servletwebrequest.requestcompleted
      webrequest.requestcompleted();
    }

    return (modelandview)result;
  }

① 此时的handlermethod是什么?

如下图所示,handlermethod里面有bean、创建bean的工厂、bean的类型、原始方法method、桥接方法bridgedmethod以及参数对象parameters等关键属性。

其他都容易理解,那么什么是bridgedmethod?(后续单独分析)

详解SpringBoot中添加@ResponseBody注解会发生什么

② 此时的servletwebrequest webrequest是什么?

这个倒是很简单,如下图所示:

详解SpringBoot中添加@ResponseBody注解会发生什么

③ 此时的webdatabinderfactory binderfactory

webdatabinderfactory binderfactory = this.getdatabinderfactory(handlermethod);

requestmappinghandleradapter.getdatabinderfactory源码如下:

private webdatabinderfactory getdatabinderfactory(handlermethod handlermethod) throws exception {
//获取handlertype 
		class<?> handlertype = handlermethod.getbeantype();
		//根据handlertype 从initbindercache获取到@initbinder注解的方法
		set<method> methods = this.initbindercache.get(handlertype);
		//如果initbindercache中没有,就从handlertype查找@initbinder注解的方法
		if (methods == null) {
			methods = methodintrospector.selectmethods(handlertype, init_binder_methods);
			this.initbindercache.put(handlertype, methods);
		}
		list<invocablehandlermethod> initbindermethods = new arraylist<>();
		//遍历controlleradvicebean的方法列表,从适合handlertype中拿到其方法列表
		//然后封装为一个个invocablehandlermethod放到initbindermethods中
		// global methods first
		this.initbinderadvicecache.foreach((controlleradvicebean, methodset) -> {
			if (controlleradvicebean.isapplicabletobeantype(handlertype)) {
				object bean = controlleradvicebean.resolvebean();
				for (method method : methodset) {
					initbindermethods.add(createinitbindermethod(bean, method));
				}
			}
		});
		for (method method : methods) {
			object bean = handlermethod.getbean();
			initbindermethods.add(createinitbindermethod(bean, method));
		}
		return createdatabinderfactory(initbindermethods);
	}

首先class<?> handlertype = handlermethod.getbeantype();通过handlermethod获取到handlertype,handlertype声明了当前完整类路径以及类上面的注解。其值如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

然后set<method> methods = this.initbindercache.get(handlertype);尝试先从initbindercache这个concurrenthashmap中获取当前类的使用了initbinder注解的方法列表。如果methods为空,则从handlertype中获取使用了@initbinder注解的方法,然后放到initbindercache中,对应代码this.initbindercache.put(handlertype, methods);

详解SpringBoot中添加@ResponseBody注解会发生什么

这个很关键。springboot请求处理流程中最重要的一步就是数据绑定,即将参数写到目标对象上面。那么这里就涉及到参数校验、数据格式转换、绑定结果对象、错误对象等。

详解SpringBoot中添加@ResponseBody注解会发生什么

最后return createdatabinderfactory(initbindermethods);其会拿到webbindinginitializer创建数据绑定工厂,。

protected initbinderdatabinderfactory createdatabinderfactory(list<invocablehandlermethod> bindermethods)
			throws exception {
		return new servletrequestdatabinderfactory(bindermethods, getwebbindinginitializer());
}

databinderfactory其属性configurablewebbindinginitializer对象提供了基础功能,该对象中webconversionservice中转换器实例如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

④ 根据handlermethod和binderfactory获取到modelfactory modelfactory

modelfactory modelfactory = this.getmodelfactory(handlermethod, binderfactory);

requestmappinghandleradapter.getmodelfactory方法源码如下:

private modelfactory getmodelfactory(handlermethod handlermethod, webdatabinderfactory binderfactory) {
//获取当前handlermethod对应的handlertype的sessionattributeshandler 
//--如果没有就创建一个new sessionattributeshandler(handlertype, this.sessionattributestore)
//参考④-①
		sessionattributeshandler sessionattrhandler = getsessionattributeshandler(handlermethod);
//获取handlertype 
		class<?> handlertype = handlermethod.getbeantype();
//获取添加了@modelattribute注解的方法		
		set<method> methods = this.modelattributecache.get(handlertype);
		if (methods == null) {
			methods = methodintrospector.selectmethods(handlertype, model_attribute_methods);
			this.modelattributecache.put(handlertype, methods);
		}
		list<invocablehandlermethod> attrmethods = new arraylist<>();
//从controlleradvicebean中获取适合当前handlertype的method,
//并封装为一个个invocablehandlermethod然后添加到attrmethods
		// global methods first
		this.modelattributeadvicecache.foreach((controlleradvicebean, methodset) -> {
			if (controlleradvicebean.isapplicabletobeantype(handlertype)) {
				object bean = controlleradvicebean.resolvebean();
				for (method method : methodset) {
					attrmethods.add(createmodelattributemethod(binderfactory, bean, method));
				}
			}
		});
//遍历methods并封装为一个个invocablehandlermethod然后添加到attrmethods
		for (method method : methods) {
			object bean = handlermethod.getbean();
			attrmethods.add(createmodelattributemethod(binderfactory, bean, method));
		}
//根据attrmethods, binderfactory, sessionattrhandler创建一个modelfactory对象
		return new modelfactory(attrmethods, binderfactory, sessionattrhandler);
	}

可以看到modelfactory主要属性modelmethods、databindfactory和sessionattributehandler都是为参数绑定数据服务的。

详解SpringBoot中添加@ResponseBody注解会发生什么

④-① requestmappinghandleradapter.getsessionattributeshandler获取给定类型的sessionattributeshandler

方法源码如下:

private modelfactory getmodelfactory(handlermethod handlermethod, webdatabinderfactory binderfactory) {
//获取当前handlermethod对应的handlertype的sessionattributeshandler 
//--如果没有就创建一个new sessionattributeshandler(handlertype, this.sessionattributestore)
//参考④-①
		sessionattributeshandler sessionattrhandler = getsessionattributeshandler(handlermethod);
//获取handlertype 
		class<?> handlertype = handlermethod.getbeantype();
//获取添加了@modelattribute注解的方法		
		set<method> methods = this.modelattributecache.get(handlertype);
		if (methods == null) {
			methods = methodintrospector.selectmethods(handlertype, model_attribute_methods);
			this.modelattributecache.put(handlertype, methods);
		}
		list<invocablehandlermethod> attrmethods = new arraylist<>();
//从controlleradvicebean中获取适合当前handlertype的method,
//并封装为一个个invocablehandlermethod然后添加到attrmethods
		// global methods first
		this.modelattributeadvicecache.foreach((controlleradvicebean, methodset) -> {
			if (controlleradvicebean.isapplicabletobeantype(handlertype)) {
				object bean = controlleradvicebean.resolvebean();
				for (method method : methodset) {
					attrmethods.add(createmodelattributemethod(binderfactory, bean, method));
				}
			}
		});
//遍历methods并封装为一个个invocablehandlermethod然后添加到attrmethods
		for (method method : methods) {
			object bean = handlermethod.getbean();
			attrmethods.add(createmodelattributemethod(binderfactory, bean, method));
		}
//根据attrmethods, binderfactory, sessionattrhandler创建一个modelfactory对象
		return new modelfactory(attrmethods, binderfactory, sessionattrhandler);
	}

④-①-①sessionattributeshandler.sessionattributeshandler

构造方法源码如下:

public sessionattributeshandler(class<?> handlertype, sessionattributestore sessionattributestore) {
		assert.notnull(sessionattributestore, "sessionattributestore may not be null");
		this.sessionattributestore = sessionattributestore;
//尝试从handlertype获取@sessionattributes注解
		sessionattributes ann = annotatedelementutils.findmergedannotation(handlertype, sessionattributes.class);
		if (ann != null) {
		//注解的name属性值放入attributenames中
			collections.addall(this.attributenames, ann.names());
		//注解的type属性值放入	attributetypes
			collections.addall(this.attributetypes, ann.types());
		}
		//把所有的attributenames放入knownattributenames
		//在初始化model方法initmodel将会使用这些数据
		this.knownattributenames.addall(this.attributenames);
	}

也就是经过③④两步,创建binderfactory、modelfactory后就会拿到匹配当前handlermethod的那些@initbinder、@modelattribute的方法(handlermethod对象)以及sessionattributeshandler !这三个东西能做什么?当你为目标方法参数绑定数据的时候就会用到!

⑤ 创建核心处理对象servletinvocablehandlermethod invocablemethod并为其属性赋值

servletinvocablehandlermethod invocablemethod = this.createinvocablehandlermethod(handlermethod);
if (this.argumentresolvers != null) {
   invocablemethod.sethandlermethodargumentresolvers(this.argumentresolvers);
 }

 if (this.returnvaluehandlers != null) {
   invocablemethod.sethandlermethodreturnvaluehandlers(this.returnvaluehandlers);
 }

 invocablemethod.setdatabinderfactory(binderfactory);
 invocablemethod.setparameternamediscoverer(this.parameternamediscoverer);

servletinvocablehandlermethod invocablemethod = this.createinvocablehandlermethod(handlermethod);创建servletinvocablehandlermethod实例:

protected handlermethod(handlermethod handlermethod) {
		assert.notnull(handlermethod, "handlermethod is required");
		this.bean = handlermethod.bean;
		this.beanfactory = handlermethod.beanfactory;
		this.beantype = handlermethod.beantype;
		this.method = handlermethod.method;
		this.bridgedmethod = handlermethod.bridgedmethod;
		this.parameters = handlermethod.parameters;
		this.responsestatus = handlermethod.responsestatus;
		this.responsestatusreason = handlermethod.responsestatusreason;
		this.description = handlermethod.description;
		this.resolvedfromhandlermethod = handlermethod.resolvedfromhandlermethod;
	}

invocablemethod.sethandlermethodargumentresolvers(this.argumentresolvers);为invocablemethod设置参数解析器组合对象-handlermethodargumentresolvercomposite。其有list<handlermethodargumentresolver> argumentresolversmap<methodparameter, handlermethodargumentresolver> argumentresolvercache两个重要属性。其中具体解析器值列表如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

我想你现在应该知道为什么方法参数使用@requestbody就可以进行参数绑定了吧!

继续看returnvaluehandlers,也就是返回结果处理器。其中returnvaluehandlers是handlermethodreturnvaluehandlercomposite实例,就像handlermethodargumentresolvercomposite一样,它包含了所有handlermethodreturnvaluehandler的列表,并在spring启动时完成注册。其值列表如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

ok,我们的主题来了。就是这个requestresponsebodymethodprocessor后置处理器对@responsebody注解进行的处理!

继续往下走,invocablemethod.setdatabinderfactory(binderfactory);给invocablemethod设置了databinderfactory。这个同上都是为数据参数绑定服务,继续往下看invocablemethod.setparameternamediscoverer(this.parameternamediscoverer);parameternamediscoverer这里值列表如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

⑥ 创建mavcontainer进行数据的初步处理

//创建modelandviewcontainer 实例对象
modelandviewcontainer mavcontainer = new modelandviewcontainer();
//从请求中获取inputflashmap并把其数据放入defaultmodel中,flashmap的作用是在redirect中传递参数
mavcontainer.addallattributes(requestcontextutils.getinputflashmap(request));
//调用modelfactory对model进行初始化
modelfactory.initmodel(webrequest, mavcontainer, invocablemethod);
//重定向时忽略默认model
mavcontainer.setignoredefaultmodelonredirect(this.ignoredefaultmodelonredirect);

首先看下modelandviewcontainer,其核心有三个属性view-视图对象,defaultmodel-默认的数据存放地方以及redirectmodel-重定向时数据存放地方。

详解SpringBoot中添加@ResponseBody注解会发生什么

modelfactory.initmodel(webrequest, mavcontainer, invocablemethod);,这里对model做了处理。也可以说是对目标方法实际调用前对数据做的最后一次处理:

public void initmodel(nativewebrequest request, modelandviewcontainer container, handlermethod handlermethod)
			throws exception {
	//获取会话属性键值对
		map<string, ?> sessionattributes = this.sessionattributeshandler.retrieveattributes(request);
		
		//对model中属性-值进行合并处理:称之为补缺更合适
		//如果model中不存在,则放入---这个很重要
		container.mergeattributes(sessionattributes);
		
		//调用标注了@modelattribute注解的方法
		invokemodelattributemethods(request, container);

		//如果handlermethod的方法参数标注了@modelattribute注解并且在sessionattributetes存在/或类型匹配,则对其进行遍历
		//尝试获取值,如果获取不到值就会抛出异常;如果获取到值就会放到model-defaultmodel中
		for (string name : findsessionattributearguments(handlermethod)) {
			if (!container.containsattribute(name)) {
				object value = this.sessionattributeshandler.retrieveattribute(request, name);
				if (value == null) {
					throw new httpsessionrequiredexception("expected session attribute '" + name + "'", name);
				}
				container.addattribute(name, value);
			}
		}
	}

map<string, ?> sessionattributes = this.sessionattributeshandler.retrieveattributes(request);获取会话属性键值对,方法源码如下:

public map<string, object> retrieveattributes(webrequest request) {
		map<string, object> attributes = new hashmap<>();
		//遍历通过@sessionattributes注解获取的name
		for (string name : this.knownattributenames) {
		//从session中获取name对应的值
			object value = this.sessionattributestore.retrieveattribute(request, name);
			if (value != null) {
			//如果值存在,则放入attributes
				attributes.put(name, value);
			}
		}
		return attributes;
	}

container.mergeattributes(sessionattributes);关于modelmap.mergeattributes合并属性方法源码如下:

#也就是说遍历sessionattributes ,如果model中不存在,就放入。如果存在,就跳过!注意,不会进行值覆盖
 public modelmap mergeattributes(@nullable map<string, ?> attributes) {
    if (attributes != null) {
      attributes.foreach((key, value) -> {
        if (!this.containskey(key)) {
          this.put(key, value);//this这里值的是modelmap,也就是defaultmodel
        }
      });
    }
    return this;
  }

这里 invokemodelattributemethods(request, container);调用了@modelattribute注解的方法,该方法通常会对model中的值进行更新。从另外一个方面来说呢,类里面的@modelattribute方法会在目标方法调用前逐个进行调用!,方法源码如下:

private void invokemodelattributemethods(nativewebrequest request, modelandviewcontainer container)
			throws exception {
//循环调用modelmethod 
		while (!this.modelmethods.isempty()) {
			invocablehandlermethod modelmethod = getnextmodelmethod(container).gethandlermethod();
			modelattribute ann = modelmethod.getmethodannotation(modelattribute.class);
			assert.state(ann != null, "no modelattribute annotation");
			if (container.containsattribute(ann.name())) {
				if (!ann.binding()) {
					container.setbindingdisabled(ann.name());
				}
				continue;
			}
			//反射调用方法并获取返回值
			object returnvalue = modelmethod.invokeforrequest(request, container);
			//如果返回值不为空,就放入model-(returnvaluename, returnvalue)
			if (!modelmethod.isvoid()){
				string returnvaluename = getnameforreturnvalue(returnvalue, modelmethod.getreturntype());
				if (!ann.binding()) {
					container.setbindingdisabled(returnvaluename);
				}
				if (!container.containsattribute(returnvaluename)) {
					container.addattribute(returnvaluename, returnvalue);
				}
			}
		}
	}

关于findsessionattributearguments方法源码如下:

//从方法参数中找到在(@sessionattributes注解的属性/参数)中存在的或者类型匹配
	 // 且方法参数上标注了@modelattribute注解的属性名集合
	private list<string> findsessionattributearguments(handlermethod handlermethod) {
		list<string> result = new arraylist<>();
		for (methodparameter parameter : handlermethod.getmethodparameters()) {
			if (parameter.hasparameterannotation(modelattribute.class)) {
				string name = getnameforparameter(parameter);
				class<?> paramtype = parameter.getparametertype();
				if (this.sessionattributeshandler.ishandlersessionattribute(name, paramtype)) {
					result.add(name);
				}
			}
		}
		return result;
	}

⑦ 异步请求

这一块先不用管,后续分析

asyncwebrequest asyncwebrequest = webasyncutils.createasyncwebrequest(request, response);
asyncwebrequest.settimeout(this.asyncrequesttimeout);

webasyncmanager asyncmanager = webasyncutils.getasyncmanager(request);
asyncmanager.settaskexecutor(this.taskexecutor);
asyncmanager.setasyncwebrequest(asyncwebrequest);
asyncmanager.registercallableinterceptors(this.callableinterceptors);
asyncmanager.registerdeferredresultinterceptors(this.deferredresultinterceptors);

if (asyncmanager.hasconcurrentresult()) {
	object result = asyncmanager.getconcurrentresult();
	mavcontainer = (modelandviewcontainer) asyncmanager.getconcurrentresultcontext()[0];
	asyncmanager.clearconcurrentresult();
	logformatutils.tracedebug(logger, traceon -> {
		string formatted = logformatutils.formatvalue(result, !traceon);
		return "resume with async result [" + formatted + "]";
	});
	invocablemethod = invocablemethod.wrapconcurrentresult(result);
}

接下来调用invocablemethod.invokeandhandle(webrequest, mavcontainer);就到了servletinvocablehandlermethod.invokeandhandle。

【3】调用目标方法并对返回值进行处理servletinvocablehandlermethod.invokeandhandle

其类继承示意图如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

servletinvocablehandlermethod.invokeandhandle方法源码如下:

public void invokeandhandle(servletwebrequest webrequest, modelandviewcontainer mavcontainer,
			object... providedargs) throws exception {
//调用目标方法并获取返回值,这里对应 【3.1】 invocablehandlermethod.invokeforrequest调用目标方法
		object returnvalue = invokeforrequest(webrequest, mavcontainer, providedargs);

//设置响应状态
		setresponsestatus(webrequest);

//如果返回值为null,则将mavcontainer.requesthandled设置为true,表示已经处理不需要视图解析
		if (returnvalue == null) {
			if (isrequestnotmodified(webrequest) || getresponsestatus() != null || mavcontainer.isrequesthandled()) {
				disablecontentcachingifnecessary(webrequest);
				mavcontainer.setrequesthandled(true);
				return;
			}
		}
		else if (stringutils.hastext(getresponsestatusreason())) {
			mavcontainer.setrequesthandled(true);
			return;
		}
//将mavcontainer.requesthandled设置为false
		mavcontainer.setrequesthandled(false);
		assert.state(this.returnvaluehandlers != null, "no return value handlers");

//返回值进行处理 ,这里对应【3.2】
		try {
			this.returnvaluehandlers.handlereturnvalue(
					returnvalue, getreturnvaluetype(returnvalue), mavcontainer, webrequest);
		}
		catch (exception ex) {
			if (logger.istraceenabled()) {
				logger.trace(formaterrorforreturnvalue(returnvalue), ex);
			}
			throw ex;
		}
	}

关于mavcontainer.setrequesthandled(false);源码如下:

public void setrequesthandled(boolean requesthandled) {
		this.requesthandled = requesthandled;
	}

检验请求添加了@responsebody注解的方法是否已经处理完,如果处理完则视图解析不再需要。当方法参数有servletresponse或者outputstream类型时,同样可以设置这个标识。requesthandled 默认值为false。

【3.1】 invocablehandlermethod.invokeforrequest调用目标方法

其方法源码如下所示,结构很清晰:获取方法参数值然后调用目标方法:

public object invokeforrequest(nativewebrequest request, @nullable modelandviewcontainer mavcontainer,
		object... providedargs) throws exception {
//解析参数--这里对应 1
	object[] args = getmethodargumentvalues(request, mavcontainer, providedargs);
	if (logger.istraceenabled()) {
		logger.trace("arguments: " + arrays.tostring(args));
	}
	//根据上面得到的参数值调用目标方法 这里对应 2 
	return doinvoke(args);
}

① 解析参数getmethodargumentvalues

protected object[] getmethodargumentvalues(nativewebrequest request, @nullable modelandviewcontainer mavcontainer,
			object... providedargs) throws exception {
//获取到方法的参数对象  methodparameter[]数组
		methodparameter[] parameters = getmethodparameters();

//如果为空,返回空参数组
		if (objectutils.isempty(parameters)) {
			return empty_args;
		}
		object[] args = new object[parameters.length];
		
		//遍历methodparameter[] parameters,对每一个方法参数对象获取到具体参数并解析得到参数值
		for (int i = 0; i < parameters.length; i++) {
			methodparameter parameter = parameters[i];
			//绑定参数名称发现器
			parameter.initparameternamediscovery(this.parameternamediscoverer);
			
			//从providedargs中尝试获取到参数名
			args[i] = findprovidedargument(parameter, providedargs);
			if (args[i] != null) {
				continue;
			}
			//如果方法参数解析器不支持parameter,则抛出异常
			if (!this.resolvers.supportsparameter(parameter)) {
				throw new illegalstateexception(formatargumenterror(parameter, "no suitable resolver"));
			}
			try {
			//使用参数解析器解析参数获取到值,下面会重点分析
				args[i] = this.resolvers.resolveargument(parameter, mavcontainer, request, this.databinderfactory);
			}
			catch (exception ex) {
				// leave stack trace for later, exception may actually be resolved and handled...
				if (logger.isdebugenabled()) {
					string exmsg = ex.getmessage();
					if (exmsg != null && !exmsg.contains(parameter.getexecutable().togenericstring())) {
						logger.debug(formatargumenterror(parameter, exmsg));
					}
				}
				throw ex;
			}
		}
		return args;
	}

methodparameter[] parameters = getmethodparameters();这里获取的 methodparameter[] parameters如下图所示:

详解SpringBoot中添加@ResponseBody注解会发生什么

参数解析器组合对象( this.resolvers)列表如下所示:

详解SpringBoot中添加@ResponseBody注解会发生什么

为什么称之为参数解析器组合对象?其实这里的this.resolvers并不是具体的参数解析器而是argumentresolvers、argumentresolvercache组合而成的handlermethodargumentresolvercomposite!

可以看到起还有argumentresolvercache属性,其值列表如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

默认argumentresolvercache是一个容量为256的concurrenthashmap,是handlermethodargumentresolvercomposite的成员变量:

private final map<methodparameter, handlermethodargumentresolver> argumentresolvercache =
			new concurrenthashmap<>(256);

这个argumentresolvercache是在动态改变,其在判断是否支持paramter的方法中会改变,handlermethodargumentresolvercomposite.getargumentresolver源码如下:

private handlermethodargumentresolver getargumentresolver(methodparameter parameter) {
//如果缓存中有,则直接返回
		handlermethodargumentresolver result = this.argumentresolvercache.get(parameter);
		//如果缓存中没有就尝试从解析器列表中获取一个支持parameter的,并将解析器 parameter放入缓存
		if (result == null) {
			for (handlermethodargumentresolver resolver : this.argumentresolvers) {
				if (resolver.supportsparameter(parameter)) {
					result = resolver;
					this.argumentresolvercache.put(parameter, result);
					break;
				}
			}
		}
		return result;
	}

为什么要有argumentresolvercache ?你可以没有,但是你就需要每次从argumentresolvers遍历寻找支持当前methodparameter的参数解析器!之所以保存一份键值对数据到argumentresolvercache ,就是为了下次不用寻找,就是为了更快!

ok ,引申多了。咱们继续回去看如何解析参数获取到参数值!

args[i] = this.resolvers.resolveargument(parameter, mavcontainer, request, this.databinderfactory);

这里会调用handlermethodargumentresolvercomposite.resolveargument方法:

public object resolveargument(methodparameter parameter, @nullable modelandviewcontainer mavcontainer,
			nativewebrequest webrequest, @nullable webdatabinderfactory binderfactory) throws exception {
		//这里获取具体的、实际的参数解析器!
		handlermethodargumentresolver resolver = getargumentresolver(parameter);
		if (resolver == null) {
			throw new illegalargumentexception("unsupported parameter type [" +
					parameter.getparametertype().getname() + "]. supportsparameter should be called first.");
		}
		return resolver.resolveargument(parameter, mavcontainer, webrequest, binderfactory);
	}

获取的实际的参数解析器如下所示(是requestresponsebodymethodprocessor):

详解SpringBoot中添加@ResponseBody注解会发生什么

调用requestresponsebodymethodprocessor.resolveargument解析参数:

public object resolveargument(methodparameter parameter, @nullable modelandviewcontainer mavcontainer,
			nativewebrequest webrequest, @nullable webdatabinderfactory binderfactory) throws exception {
		//这里获取具体的、实际的参数解析器!
		handlermethodargumentresolver resolver = getargumentresolver(parameter);
		if (resolver == null) {
			throw new illegalargumentexception("unsupported parameter type [" +
					parameter.getparametertype().getname() + "]. supportsparameter should be called first.");
		}
		return resolver.resolveargument(parameter, mavcontainer, webrequest, binderfactory);
	}

获取方法参数变量名称string name = conventions.getvariablenameforparameter(parameter);conventions.getvariablenameforparameter方法源码如下:

public static string getvariablenameforparameter(methodparameter parameter) {
		assert.notnull(parameter, "methodparameter must not be null");
		class<?> valueclass;
		boolean pluralize = false;
		string reactivesuffix = "";
//判断参数类型是不是数组
		if (parameter.getparametertype().isarray()) {
			valueclass = parameter.getparametertype().getcomponenttype();
			pluralize = true;
		}
		// 判断是不是集合类型
		else if (collection.class.isassignablefrom(parameter.getparametertype())) {
			valueclass = resolvabletype.formethodparameter(parameter).ascollection().resolvegeneric();
			if (valueclass == null) {
				throw new illegalargumentexception(
						"cannot generate variable name for non-typed collection parameter type");
			}
			pluralize = true;
		}
		else {
		//获取参数类型,这里是com.alibaba.fastjson.jsonobject
			valueclass = parameter.getparametertype();
			reactiveadapter adapter = reactiveadapterregistry.getsharedinstance().getadapter(valueclass);
			if (adapter != null && !adapter.getdescriptor().isnovalue()) {
				reactivesuffix = classutils.getshortname(valueclass);
				valueclass = parameter.nested().getnestedparametertype();
			}
		}
		string name = classutils.getshortnameasproperty(valueclass);
		return (pluralize ? pluralize(name) : name + reactivesuffix);
	}

拿到参数变量名与参数值后,就会进行数据绑定过程。在这个过程中会使用binderfactory创建webdatabinder对象,然后使用webbindinginitializer对其进行初始化。

if (binderfactory != null) {
			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());
				}
			}
			if (mavcontainer != null) {
				mavcontainer.addattribute(bindingresult.model_key_prefix + name, binder.getbindingresult());
			}
		}

首先我们看一下webdatabinder实例对象创建过程。defaultdatabinderfactory.createbinder方法源码如下:

public final webdatabinder createbinder(
			nativewebrequest webrequest, @nullable object target, string objectname) throws exception {
//创建webdatabinder 实例
		webdatabinder databinder = createbinderinstance(target, objectname, webrequest);
		//如果初始化器不为null,进行初始化
		if (this.initializer != null) {
			this.initializer.initbinder(databinder, webrequest);
		}
		//这是扩展接口,可以用户自定义以进行更深入的初始化
		initbinder(databinder, webrequest);
		return databinder;
	}

继续跟createbinderinstance(target, objectname, webrequest);,其会走到servletrequestdatabinderfactory.createbinderinstance方法,如下所示:

详解SpringBoot中添加@ResponseBody注解会发生什么

可以发现器创建了一个extendedservletrequestdatabinder实例对象,其类继承图如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

创建extendedservletrequestdatabinder实例对象时,一路调用父类的构造方法,最终跟到databinder类中:

public databinder(@nullable object target, string objectname) {
    this.ignoreunknownfields = true;
    this.ignoreinvalidfields = false;
    this.autogrownestedpaths = true;
    this.autogrowcollectionlimit = 256;
    this.bindingerrorprocessor = new defaultbindingerrorprocessor();
    this.validators = new arraylist();
    this.target = objectutils.unwrapoptional(target);
    this.objectname = objectname;
  }

创建完数据绑定器后,就使用初始化器对其进行初始化,configurablewebbindinginitializer.initbinder方法如下所示:

public void initbinder(webdatabinder binder) {
		binder.setautogrownestedpaths(this.autogrownestedpaths);
		if (this.directfieldaccess) {
			binder.initdirectfieldaccess();
		}
		if (this.messagecodesresolver != null) {
			binder.setmessagecodesresolver(this.messagecodesresolver);
		}
		if (this.bindingerrorprocessor != null) {
			binder.setbindingerrorprocessor(this.bindingerrorprocessor);
		}
		//如果target不为null且校验器不为空,就绑定校验器
		if (this.validator != null && binder.gettarget() != null &&
				this.validator.supports(binder.gettarget().getclass())) {
			binder.setvalidator(this.validator);
		}
		//绑定类型转换服务类
		if (this.conversionservice != null) {
			binder.setconversionservice(this.conversionservice);
		}
		if (this.propertyeditorregistrars != null) {
			for (propertyeditorregistrar propertyeditorregistrar : this.propertyeditorregistrars) {
				propertyeditorregistrar.registercustomeditors(binder);
			}
		}
	}

代码如下所示,初始化完webdatabinder后,就尝试使用binder的校验器对parameter进行校验(如果参数使用了@valid注解或者以valid开头的注解)。校验完后就会获取org.springframework.validation.beanpropertybindingresult,如果beanpropertybindingresult有错误且你并没有用一个errors对象的参数接收异常,那么就会抛出methodargumentnotvalidexception异常!

public void initbinder(webdatabinder binder) {
		binder.setautogrownestedpaths(this.autogrownestedpaths);
		if (this.directfieldaccess) {
			binder.initdirectfieldaccess();
		}
		if (this.messagecodesresolver != null) {
			binder.setmessagecodesresolver(this.messagecodesresolver);
		}
		if (this.bindingerrorprocessor != null) {
			binder.setbindingerrorprocessor(this.bindingerrorprocessor);
		}
		//如果target不为null且校验器不为空,就绑定校验器
		if (this.validator != null && binder.gettarget() != null &&
				this.validator.supports(binder.gettarget().getclass())) {
			binder.setvalidator(this.validator);
		}
		//绑定类型转换服务类
		if (this.conversionservice != null) {
			binder.setconversionservice(this.conversionservice);
		}
		if (this.propertyeditorregistrars != null) {
			for (propertyeditorregistrar propertyeditorregistrar : this.propertyeditorregistrars) {
				propertyeditorregistrar.registercustomeditors(binder);
			}
		}
	}

数据绑定这一块就是参数从形参变为实参的最后一步!如何把请求中的参数值赋给方法的形参,就是通过webdatabinder 这个对象实现的!可以看下此时binder对象:

详解SpringBoot中添加@ResponseBody注解会发生什么

有了绑定结果后的binder:

详解SpringBoot中添加@ResponseBody注解会发生什么

继续往下走mavcontainer.addattribute(bindingresult.model_key_prefix + name, binder.getbindingresult());把绑定结果放到model中:

详解SpringBoot中添加@ResponseBody注解会发生什么

ok!回到handlermethodargumentresolvercomposite.resolveargument!

详解SpringBoot中添加@ResponseBody注解会发生什么

然后继续回到invocablehandlermethod.getmethodargumentvalues中:

详解SpringBoot中添加@ResponseBody注解会发生什么

因为本次请求的目标方法只有一个参数,则其会继续返回到invocablehandlermethod.invokeforrequest,也就是说到此,① 已经结束!

详解SpringBoot中添加@ResponseBody注解会发生什么

② 根据参数值反射调用目标方法

invocablehandlermethod.doinvoke方法源码如下:

protected object doinvoke(object... args) throws exception {
//获取桥接方法并使方法可以调用
		reflectionutils.makeaccessible(getbridgedmethod());
		try {
//		获取桥接方法以及对应的bean 参数值,然后反射调用
			return getbridgedmethod().invoke(getbean(), args);
		}
		catch (illegalargumentexception ex) {
			asserttargetbean(getbridgedmethod(), getbean(), args);
			string text = (ex.getmessage() != null ? ex.getmessage() : "illegal argument");
			throw new illegalstateexception(formatinvokeerror(text, args), ex);
		}
		catch (invocationtargetexception ex) {
			// unwrap for handlerexceptionresolvers ...
			throwable targetexception = ex.gettargetexception();
			if (targetexception instanceof runtimeexception) {
				throw (runtimeexception) targetexception;
			}
			else if (targetexception instanceof error) {
				throw (error) targetexception;
			}
			else if (targetexception instanceof exception) {
				throw (exception) targetexception;
			}
			else {
				throw new illegalstateexception(formatinvokeerror("invocation failure", args), targetexception);
			}
		}
	}

这里就会反射调用目标方法进行处理!处理完后会再次返回,一直返回到servletinvocablehandlermethod.invokeandhandle!

详解SpringBoot中添加@ResponseBody注解会发生什么

到此【3.1】结束!已经调用了目标方法并获取到了目标方法返回值!

【3.2】返回结果处理

servletinvocablehandlermethod.invokeandhandle方法首先会反射调用目标方法,然后拿到方法返回值。最后会根据returnvaluehandlers对返回结果进行处理!

this.returnvaluehandlers.handlereturnvalue(
returnvalue, getreturnvaluetype(returnvalue), mavcontainer, webrequest);

这里this.returnvaluehandlers同样是一个返回结果处理器组合对象,值列表如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

① 获取返回结果类型

handlermethod.getreturnvaluetype源码如下:

public methodparameter getreturnvaluetype(@nullable object returnvalue) {
		return new returnvaluemethodparameter(returnvalue);
	}

returnvaluemethodparameter是handlermethod的内部类,并继承自handlermethod.handlermethodparameter(没错,这货也是handlermethod的内部类):

private class returnvaluemethodparameter extends handlermethodparameter {

		@nullable
		private final object returnvalue;

		public returnvaluemethodparameter(@nullable object returnvalue) {
			super(-1);
			this.returnvalue = returnvalue;
		}

		protected returnvaluemethodparameter(returnvaluemethodparameter original) {
			super(original);
			this.returnvalue = original.returnvalue;
		}

		@override
		public class<?> getparametertype() {
			return (this.returnvalue != null ? this.returnvalue.getclass() : super.getparametertype());
		}

		@override
		public returnvaluemethodparameter clone() {
			return new returnvaluemethodparameter(this);
		}
	}

详解SpringBoot中添加@ResponseBody注解会发生什么

② 选择handlermethodreturnvaluehandler

handlermethodreturnvaluehandlercomposite.handlereturnvalue方法源码如下:

private class returnvaluemethodparameter extends handlermethodparameter {

		@nullable
		private final object returnvalue;

		public returnvaluemethodparameter(@nullable object returnvalue) {
			super(-1);
			this.returnvalue = returnvalue;
		}

		protected returnvaluemethodparameter(returnvaluemethodparameter original) {
			super(original);
			this.returnvalue = original.returnvalue;
		}

		@override
		public class<?> getparametertype() {
			return (this.returnvalue != null ? this.returnvalue.getclass() : super.getparametertype());
		}

		@override
		public returnvaluemethodparameter clone() {
			return new returnvaluemethodparameter(this);
		}
	}

这里returntype如下所示,其是handlermethod$returnvaluemethodparameter对象:

详解SpringBoot中添加@ResponseBody注解会发生什么

这里寻找到的handler是requestresponsebodymethodprocessor

详解SpringBoot中添加@ResponseBody注解会发生什么

还记得上面解析参数时,咱们获取到的实际参数解析器也是这个requestresponsebodymethodprocessor!

详解SpringBoot中添加@ResponseBody注解会发生什么

也就是说requestresponsebodymethodprocessor就是用来处理@requestbody和@responsebody的!它可以使用httpmessageconverter从请求中读数据赋给参数,并可以把返回结果扔给响应。httpmessageconverter在这中间起到了什么作用呢?顾名思义,数据格式转换!

其类结构继承图如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

③ 返回结果写到outputmessage中

requestresponsebodymethodprocessor.handlereturnvalue源码如下:

@override
public void handlereturnvalue(@nullable object returnvalue, methodparameter returntype,
	modelandviewcontainer mavcontainer, nativewebrequest webrequest)
	throws ioexception, httpmediatypenotacceptableexception, httpmessagenotwritableexception {
//设置请求已经被处理
mavcontainer.setrequesthandled(true);

//获取一个servletserverhttprequest实例-构造函数参数为httpservletrequest
servletserverhttprequest inputmessage = createinputmessage(webrequest);
//获取一个 实例servletserverhttpresponse ,构造函数参数为httpservletresponse
servletserverhttpresponse outputmessage = createoutputmessage(webrequest);

// try even with null return value. responsebodyadvice could get involved.
writewithmessageconverters(returnvalue, returntype, inputmessage, outputmessage);
}

记得在上面解析参数的时候调用过readwithmessageconverters方法,那时是从请求中获取数据。这里返回响应信息需要把返回结果写到响应体中。

详解SpringBoot中添加@ResponseBody注解会发生什么

abstractmessageconvertermethodprocessor.writewithmessageconverters源码如下:

protected <t> void writewithmessageconverters(@nullable t value, methodparameter returntype,
			servletserverhttprequest inputmessage, servletserverhttpresponse outputmessage)
			throws ioexception, httpmediatypenotacceptableexception, httpmessagenotwritableexception {

		object body;
		class<?> valuetype;
		type targettype;

		if (value instanceof charsequence) {
			body = value.tostring();
			valuetype = string.class;
			targettype = string.class;
		}
		else {
			body = value;
//值类型,这里是class com.baby.healthcare.common.responsebean
			valuetype = getreturnvaluetype(body, returntype);
			targettype = generictyperesolver.resolvetype(getgenerictype(returntype), returntype.getcontainingclass());
		}
//判断是否resource 或inputstreamsource
		if (isresourcetype(value, returntype)) {
			outputmessage.getheaders().set(httpheaders.accept_ranges, "bytes");
			if (value != null && inputmessage.getheaders().getfirst(httpheaders.range) != null &&
					outputmessage.getservletresponse().getstatus() == 200) {
				resource resource = (resource) value;
				try {
					list<httprange> httpranges = inputmessage.getheaders().getrange();
					outputmessage.getservletresponse().setstatus(httpstatus.partial_content.value());
					body = httprange.toresourceregions(httpranges, resource);
					valuetype = body.getclass();
					targettype = resource_region_list_type;
				}
				catch (illegalargumentexception ex) {
					outputmessage.getheaders().set(httpheaders.content_range, "bytes */" + resource.contentlength());
					outputmessage.getservletresponse().setstatus(httpstatus.requested_range_not_satisfiable.value());
				}
			}
		}

		mediatype selectedmediatype = null;
//响应内容类型
		mediatype contenttype = outputmessage.getheaders().getcontenttype();
		boolean iscontenttypepreset = contenttype != null && contenttype.isconcrete();
		if (iscontenttypepreset) {
			if (logger.isdebugenabled()) {
				logger.debug("found 'content-type:" + contenttype + "' in response");
			}
			selectedmediatype = contenttype;
		}
		else {
			httpservletrequest request = inputmessage.getservletrequest();
			//获取接收的mediatype
			list<mediatype> acceptabletypes = getacceptablemediatypes(request);
			//获取返回结果的mediatype
			list<mediatype> producibletypes = getproduciblemediatypes(request, valuetype, targettype);
//如果body不为空,但是没有合适的返回结果类型,则抛出异常
			if (body != null && producibletypes.isempty()) {
				throw new httpmessagenotwritableexception(
						"no converter found for return value of type: " + valuetype);
			}
//循环比较,从acceptabletypes找到适配producibletypes的
			list<mediatype> mediatypestouse = new arraylist<>();
			for (mediatype requestedtype : acceptabletypes) {
				for (mediatype producibletype : producibletypes) {
					if (requestedtype.iscompatiblewith(producibletype)) {
						mediatypestouse.add(getmostspecificmediatype(requestedtype, producibletype));
					}
				}
			}
			if (mediatypestouse.isempty()) {
				if (body != null) {
					throw new httpmediatypenotacceptableexception(producibletypes);
				}
				if (logger.isdebugenabled()) {
					logger.debug("no match for " + acceptabletypes + ", supported: " + producibletypes);
				}
				return;
			}
//对mediatype进行排序
			mediatype.sortbyspecificityandquality(mediatypestouse);

			for (mediatype mediatype : mediatypestouse) {
				if (mediatype.isconcrete()) {
					selectedmediatype = mediatype;
					break;
				}
				else if (mediatype.ispresentin(all_application_media_types)) {
					selectedmediatype = mediatype.application_octet_stream;
					break;
				}
			}

			if (logger.isdebugenabled()) {
				logger.debug("using '" + selectedmediatype + "', given " +
						acceptabletypes + " and supported " + producibletypes);
			}
		}

		if (selectedmediatype != null) {
			selectedmediatype = selectedmediatype.removequalityvalue();
			for (httpmessageconverter<?> converter : this.messageconverters) {
				generichttpmessageconverter genericconverter = (converter instanceof generichttpmessageconverter ?
						(generichttpmessageconverter<?>) converter : null);
				if (genericconverter != null ?
						((generichttpmessageconverter) converter).canwrite(targettype, valuetype, selectedmediatype) :
						converter.canwrite(valuetype, selectedmediatype)) {
					body = getadvice().beforebodywrite(body, returntype, selectedmediatype,
							(class<? extends httpmessageconverter<?>>) converter.getclass(),
							inputmessage, outputmessage);
					if (body != null) {
						object thebody = body;
						logformatutils.tracedebug(logger, traceon ->
								"writing [" + logformatutils.formatvalue(thebody, !traceon) + "]");
						addcontentdispositionheader(inputmessage, outputmessage);
						if (genericconverter != null) {
							genericconverter.write(body, targettype, selectedmediatype, outputmessage);
						}
						else {
							((httpmessageconverter) converter).write(body, selectedmediatype, outputmessage);
						}
					}
					else {
						if (logger.isdebugenabled()) {
							logger.debug("nothing to write: null body");
						}
					}
					return;
				}
			}
		}

		if (body != null) {
			set<mediatype> produciblemediatypes =
					(set<mediatype>) inputmessage.getservletrequest()
							.getattribute(handlermapping.producible_media_types_attribute);

			if (iscontenttypepreset || !collectionutils.isempty(produciblemediatypes)) {
				throw new httpmessagenotwritableexception(
						"no converter for [" + valuetype + "] with preset content-type '" + contenttype + "'");
			}
			throw new httpmediatypenotacceptableexception(this.allsupportedmediatypes);
		}
	}

关于mediatype、mimetype与conttype对照表可以参考博文:contenttype与mime对照表

详解SpringBoot中添加@ResponseBody注解会发生什么

循环比较,从acceptabletypes找到适配producibletypes的:

//循环比较,从acceptabletypes找到适配producibletypes的
			list<mediatype> mediatypestouse = new arraylist<>();
			for (mediatype requestedtype : acceptabletypes) {
				for (mediatype producibletype : producibletypes) {
					if (requestedtype.iscompatiblewith(producibletype)) {
						mediatypestouse.add(getmostspecificmediatype(requestedtype, producibletype));
					}
				}
			}

请求接收的内容类型与返回响应的内容类型如下所示:

详解SpringBoot中添加@ResponseBody注解会发生什么

mediatype.sortbyspecificityandquality(mediatypestouse);对mediatypestouse进行排序,排序后的效果如下所示:

详解SpringBoot中添加@ResponseBody注解会发生什么

寻找合适的转换器把body写到outputmessage中:

for (httpmessageconverter<?> converter : this.messageconverters) {
generichttpmessageconverter genericconverter = (converter instanceof generichttpmessageconverter ?
			(generichttpmessageconverter<?>) converter : null);
	if (genericconverter != null ?
			((generichttpmessageconverter) converter).canwrite(targettype, valuetype, selectedmediatype) :
			converter.canwrite(valuetype, selectedmediatype)) {
		body = getadvice().beforebodywrite(body, returntype, selectedmediatype,
				(class<? extends httpmessageconverter<?>>) converter.getclass(),
				inputmessage, outputmessage);
		if (body != null) {
			object thebody = body;
			logformatutils.tracedebug(logger, traceon ->
					"writing [" + logformatutils.formatvalue(thebody, !traceon) + "]");
			addcontentdispositionheader(inputmessage, outputmessage);
			if (genericconverter != null) {
				genericconverter.write(body, targettype, selectedmediatype, outputmessage);
			}
			else {
				((httpmessageconverter) converter).write(body, selectedmediatype, outputmessage);
			}
		}
		else {
			if (logger.isdebugenabled()) {
				logger.debug("nothing to write: null body");
			}
		}
		return;
	}
}

这里遍历的messageconverters如下所示:

详解SpringBoot中添加@ResponseBody注解会发生什么

genericconverter.write(body, targettype, selectedmediatype, outputmessage);最后使用mappingjackson2httpmessageconverter把body写到outputmessage中。其类结构继承示意图如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

往响应输出流中写完返回结果并flush后就会依次返回,此时【3.2】handlermethodreturnvaluehandlercomposite.handlereturnvalue返回结果处理执行完毕!

然后返回到servletinvocablehandlermethod.invokeandhandle,此时【3】执行完毕!

【4】requestmappinghandleradapter.getmodelandview尝试获取视图对象

requestmappinghandleradapter.getmodelandview方法源码如下:

@nullable
private modelandview getmodelandview(modelandviewcontainer mavcontainer,
		modelfactory modelfactory, nativewebrequest webrequest) throws exception {
//更新model
	modelfactory.updatemodel(webrequest, mavcontainer);
	//如果请求已经处理完,则直接返回,不会再尝试创建mav 
	if (mavcontainer.isrequesthandled()) {
		return null;
	}
	modelmap model = mavcontainer.getmodel();
	modelandview mav = new modelandview(mavcontainer.getviewname(), model, mavcontainer.getstatus());
	if (!mavcontainer.isviewreference()) {
		mav.setview((view) mavcontainer.getview());
	}
	if (model instanceof redirectattributes) {
		map<string, ?> flashattributes = ((redirectattributes) model).getflashattributes();
		httpservletrequest request = webrequest.getnativerequest(httpservletrequest.class);
		if (request != null) {
			requestcontextutils.getoutputflashmap(request).putall(flashattributes);
		}
	}
	return mav;
}

modelfactory.updatemodel(webrequest, mavcontainer);更新model

  • @sessionattributes注解的属性键值对放到session中;
  • 如果请求没有处理完毕,则尝试更新model中的bindingresult

② 如果请求处理完毕,则直接返回null

如下图所示,在【3.2】-③中handlereturnvalue首先将requesthandled设置为true。那么自然不会往下走去获取视图名并尝试解析

详解SpringBoot中添加@ResponseBody注解会发生什么

【5】servletwebrequest.requestcompleted

servletwebrequest类继承示意图如下:

详解SpringBoot中添加@ResponseBody注解会发生什么

其会直接调用abstractrequestattributes.requestcompleted,方法源码如下:

#标记这个请求已经被完成
##调用所有的销毁回调方法
##更新请求过程中访问到的会话属性
public void requestcompleted() {
		executerequestdestructioncallbacks();
		updateaccessedsessionattributes();
		this.requestactive = false;
	}

abstractrequestattributes.executerequestdestructioncallbacks源码如下,其会遍历requestdestructioncallbacks并依次执行每个runnable。

private void executerequestdestructioncallbacks() {
//这里使用synchronized 保证每个runnable 只被调用一次
	synchronized (this.requestdestructioncallbacks) {
		for (runnable runnable : this.requestdestructioncallbacks.values()) {
			runnable.run();
		}
		this.requestdestructioncallbacks.clear();
	}
}

然后依次返回到requestmappinghandleradapter.handleinternal也就是【1】-②:

详解SpringBoot中添加@ResponseBody注解会发生什么

如果响应头中不包含缓存控制cache-control,则尝试对response进行cache-control设置:

if (!response.containsheader(header_cache_control)) {
	if (getsessionattributeshandler(handlermethod).hassessionattributes()) {
			applycacheseconds(response, this.cachesecondsforsessionattributehandlers);
		}
		else {
			prepareresponse(response);
		}
}

然后会返回到abstracthandlermethodadapter.handle方法,然后回到dispatcherservlet.dodispatch,这是获取到的mv为null。

详解SpringBoot中添加@ResponseBody注解会发生什么

【6】dispatcherservlet剩下的处理

① applydefaultviewname(processedrequest, mv);尝试获取视图名字

源码如下所示,这里mv为null,自然不存在view name。

private void applydefaultviewname(httpservletrequest request, @nullable modelandview mv) throws exception {
		if (mv != null && !mv.hasview()) {
			string defaultviewname = getdefaultviewname(request);
			if (defaultviewname != null) {
				mv.setviewname(defaultviewname);
			}
		}
	}

② mappedhandler.applyposthandle(processedrequest, response, mv);方法后置处理

其实就是执行拦截器的后置方法posthandle,handlerexecutionchain.applyposthandle源码如下:

void applyposthandle(httpservletrequest request, httpservletresponse response, @nullable modelandview mv)
			throws exception {

		handlerinterceptor[] interceptors = getinterceptors();
		if (!objectutils.isempty(interceptors)) {
			for (int i = interceptors.length - 1; i >= 0; i--) {
				handlerinterceptor interceptor = interceptors[i];
				interceptor.posthandle(request, response, this.handler, mv);
			}
		}
	}

③ processdispatchresult(processedrequest, response, mappedhandler, mv, dispatchexception);

如果存在异常,则mv为 ((modelandviewdefiningexception) exception).getmodelandview();然后进行render(mv, request, response);;

如果不存在异常,且mv不为null,则进行render(mv, request, response);;

如果mv不存在,则不会进行render(mv, request, response);;,其会直接调用mappedhandler.triggeraftercompletion(request, response, null);

private void processdispatchresult(httpservletrequest request, httpservletresponse response,
			@nullable handlerexecutionchain mappedhandler, @nullable modelandview mv,
			@nullable exception exception) throws exception {

		boolean errorview = false;

		if (exception != null) {
			if (exception instanceof modelandviewdefiningexception) {
				logger.debug("modelandviewdefiningexception encountered", exception);
				mv = ((modelandviewdefiningexception) exception).getmodelandview();
			}
			else {
				object handler = (mappedhandler != null ? mappedhandler.gethandler() : null);
				mv = processhandlerexception(request, response, handler, exception);
				errorview = (mv != null);
			}
		}

		// did the handler return a view to render?
		if (mv != null && !mv.wascleared()) {
			render(mv, request, response);
			if (errorview) {
				webutils.clearerrorrequestattributes(request);
			}
		}
		else {
			if (logger.istraceenabled()) {
				logger.trace("no view rendering, null modelandview returned.");
			}
		}

		if (webasyncutils.getasyncmanager(request).isconcurrenthandlingstarted()) {
			// concurrent handling started during a forward
			return;
		}

		if (mappedhandler != null) {
			// exception (if any) is already handled..
			mappedhandler.triggeraftercompletion(request, response, null);
		}
	}

拦截器的完成方法aftercompletion调用,handlerexecutionchain.triggeraftercompletion方法源码如下:

void triggeraftercompletion(httpservletrequest request, httpservletresponse response, @nullable exception ex)
		throws exception {

	handlerinterceptor[] interceptors = getinterceptors();
	if (!objectutils.isempty(interceptors)) {
		for (int i = this.interceptorindex; i >= 0; i--) {
			handlerinterceptor interceptor = interceptors[i];
			try {
				interceptor.aftercompletion(request, response, this.handler, ex);
			}
			catch (throwable ex2) {
				logger.error("handlerinterceptor.aftercompletion threw exception", ex2);
			}
		}
	}
}

最后执行finally 里面的逻辑:

if (asyncmanager.isconcurrenthandlingstarted()) {
	// instead of posthandle and aftercompletion
	if (mappedhandler != null) {
		mappedhandler.applyafterconcurrenthandlingstarted(processedrequest, response);
	}
}else {
	// clean up any resources used by a multipart request.
	if (multipartrequestparsed) {
		cleanupmultipart(processedrequest);
	}
}

到此这篇关于详解springboot中添加@responsebody注解会发生什么的文章就介绍到这了,更多相关springboot添加@responsebody内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!