• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

springboot 搞代码 4年前 (2022-01-09) 17次浏览 已收录 0个评论

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进行处理。

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

可以看到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方法进行实际业本文来源[email protected]搞@^&代*@码)网5务处理。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:详解SpringBoot中添加@ResponseBody注解会发生什么

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址