定义返回值类型处理器的组合;
public static HandlerMethodReturnValueHandlerComposite getReturnValueHandler(){HandlerMethodReturnValueHandlerComposite composite = new HandlerMethodReturnValueHandlerComposite();// 处理ModelAndViewcomposite.addHandler(new ModelAndViewMethodReturnValueHandler());// 解析不加任何注解的返回把返回的String当作视图名composite.addHandler(new ViewNameMethodReturnValueHandler());// 处理带有@ModelAttribute注解的composite.addHandler(new ServletModelAttributeMethodProcessor(false));composite.addHandler(new HttpEntityMethodProcessor(List.of(new MappingJackson2HttpMessageConverter())));composite.addHandler(new HttpHeadersReturnValueHandler());// 将返回值当成响应体 然后经过MessageConverter转换为jsoncomposite.addHandler(new RequestResponseBodyMethodProcessor(List.of(new MappingJackson2HttpMessageConverter())));// 处理不带有@ModelAttribute注解的composite.addHandler(new ServletModelAttributeMethodProcessor(true));return composite;
}
测试使用的controller
static class Controller{public ModelAndView test1(){ModelAndView mav = new ModelAndView("view1");mav.addObject("name","张三");return mav;}public String test2(){return "view2";}
}
测试方法
public static void main(String[] args) throws Exception {AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext(WebConfig.class);Method method = Controller.class.getMethod("test1");Controller controller = new Controller();//返回值Object returnValue = method.invoke(controller);// 处理方法的类HandlerMethod methodHandle = new HandlerMethod(controller,method);// mav containerModelAndViewContainer container = new ModelAndViewContainer();HandlerMethodReturnValueHandlerComposite composite = getReturnValueHandler();// 判断当前返回值类型是否支持if (composite.supportsReturnType(methodHandle.getReturnType())) {composite.handleReturnValue(returnValue,methodHandle.getReturnType(),container,new ServletWebRequest(new MockHttpServletRequest()));}
}
MessageConverter
这个处理器会将数据转换为响应体数据;
composite.addHandler(new RequestResponseBodyMethodProcessor(List.of(new MappingJackson2HttpMessageConverter())));
通过MessageConverter将消息转换为json相应数据。
返回值处理器通过消息转换器将消息类型转为指定的格式;
如果一个返回值处理器中设置了多个消息转换器怎么进行转换呢?
对于这种情况如果默认请求头和contentType没有设置的话默认返回第一个消息类型;
request.addHeader("Accept","application/xml");
如果设置了请求头那么这种情况会转为xml;
request.addHeader("application/json")
如果设置了contentType则这个优先级最高返回json;