SpringMVC 请求、响应流程
来源:互联网 发布:安索夫矩阵 编辑:程序博客网 时间:2024/04/29 15:56
概述
在SpringMVC中,可以使用@RequestBody和@ResponseBody两个注解,分别完成请求报文到对象和对象到响应报文的转换,底层这种灵活的消息转换机制,就是Spring3.x中新引入的HttpMessageConverter即消息转换器机制。
先看一下流程图:
Http请求的抽象
还是回到请求-响应,也就是解析请求体,然后返回响应报文这个最基本的Http请求过程中来。我们知道,在servlet标准中,可以用javax.servlet.ServletRequest接口中的以下方法:
/** * Retrieves the body of the request as binary data using * a {@link ServletInputStream}. Either this method or * {@link #getReader} may be called to read the body, not both. * * @return a {@link ServletInputStream} object containing * the body of the request * * @exception IllegalStateException if the {@link #getReader} method * has already been called for this request * * @exception IOException if an input or output exception occurred */ public ServletInputStream getInputStream() throws IOException;
/** * Returns a {@link ServletOutputStream} suitable for writing binary * data in the response. The servlet container does not encode the * binary data. * * <p> Calling flush() on the ServletOutputStream commits the response. * * Either this method or {@link #getWriter} may * be called to write the body, not both, except when {@link #reset} * has been called. * * @return a {@link ServletOutputStream} for writing binary data * * @exception IllegalStateException if the <code>getWriter</code> method * has been called on this response * * @exception IOException if an input or output exception occurred * * @see #getWriter * @see #reset */ public ServletOutputStream getOutputStream() throws IOException;
来得到一个ServletOutputStream,这个ServletOutputSteam,继承自java中的OutputStream,可以让你输出Http的响应报文内容。
让我们尝试着像SpringMVC的设计者一样来思考一下。我们知道,Http请求和响应报文本质上都是一串字符串,当请求报文来到java世界,它会被封装成为一个ServletInputStream的输入流,供我们读取报文。响应报文则是通过一个ServletOutputStream的输出流,来输出响应报文。
我们从流中,只能读取到原始的字符串报文,同样,我们往输出流中,也只能写原始的字符。而在java世界中,处理业务逻辑,都是以一个个有业务意义的对象为处理维度的,那么在报文到达SpringMVC和从SpringMVC出去,都存在一个字符串到java对象的阻抗问题。这一过程,不可能由开发者手工转换。我们知道,在Struts2中,采用了OGNL来应对这个问题,而在SpringMVC中,它是HttpMessageConverter机制。我们先来看两个接口。
HttpInputMessage
这个类是SpringMVC内部对一次Http请求报文的抽象,在HttpMessageConverter的read()方法中,有一个HttpInputMessage的形参,它正是SpringMVC的消息转换器所作用的受体“请求消息”的内部抽象,消息转换器从“请求消息”中按照规则提取消息,转换为方法形参中声明的对象。
HttpMessageConverter
对消息转换器最高层次的接口抽象,描述了一个消息转换器的一般特征,我们可以从这个接口中定义的方法,来领悟Spring3.x的设计者对这一机制的思考过程。
/** * Strategy interface that specifies a converter that can convert from and to HTTP requests and responses. * * @author Arjen Poutsma * @author Juergen Hoeller * @since 3.0 */public interface HttpMessageConverter<T> {boolean canRead(Class<?> clazz, MediaType mediaType);boolean canWrite(Class<?> clazz, MediaType mediaType);List<MediaType> getSupportedMediaTypes();T read(Class<? extends T> clazz, HttpInputMessage inputMessage)throws IOException, HttpMessageNotReadableException;void write(T t, MediaType contentType, HttpOutputMessage outputMessage)throws IOException, HttpMessageNotWritableException;}
HttpMessageConverter接口的定义出现了成对的canRead(),read()和canWrite(),write()方法,MediaType是对请求的Media Type属性的封装。举个例子,当我们声明了下面这个处理方法。
@RequestMapping(value="/string", method=RequestMethod.POST)public @ResponseBody String readString(@RequestBody String string) { return "Read string '" + string + "'";}
在SpringMVC进入readString方法前,会根据@RequestBody注解选择适当的HttpMessageConverter实现类来将请求参数解析到string变量中,具体来说是使用了StringHttpMessageConverter类,它的canRead()方法返回true,然后它的read()方法会从请求中读出请求参数,绑定到readString()方法的string变量中。
当SpringMVC执行readString方法后,由于返回值标识了@ResponseBody,SpringMVC将使用StringHttpMessageConverter的write()方法,将结果作为String值写入响应报文,当然,此时canWrite()方法返回true。
RequestResponseBodyMethodProcessor
将上述过程集中描述的一个类是org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor,这个类同时实现了HandlerMethodArgumentResolver和HandlerMethodReturnValueHandler两个接口。前者是将请求报文绑定到处理方法形参的策略接口,后者则是对处理方法返回值进行处理的策略接口。两个接口的源码如下:
public interface HandlerMethodArgumentResolver { boolean supportsParameter(MethodParameter parameter); Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception;}
public interface HandlerMethodReturnValueHandler { boolean supportsReturnType(MethodParameter returnType); void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception;}
RequestResponseBodyMethodProcessor这个类,同时充当了方法参数解析和返回值处理两种角色。我们从它的源码中,可以找到上面两个接口的方法实现。
对HandlerMethodArgumentResolver接口的实现:
public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(RequestBody.class);}public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Object argument = readWithMessageConverters(webRequest, parameter, parameter.getGenericParameterType()); String name = Conventions.getVariableNameForParameter(parameter); WebDataBinder binder = binderFactory.createBinder(webRequest, argument, name); if (argument != null) { validate(binder, parameter); } mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult()); return argument;}
对HandlerMethodReturnValueHandler接口的实现
public boolean supportsReturnType(MethodParameter returnType) { return returnType.getMethodAnnotation(ResponseBody.class) != null;} public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws IOException, HttpMediaTypeNotAcceptableException { mavContainer.setRequestHandled(true); if (returnValue != null) { writeWithMessageConverters(returnValue, returnType, webRequest); }}
看完上面的代码,整个HttpMessageConverter消息转换的脉络已经非常清晰。因为两个接口的实现,分别是以是否有@RequestBody和@ResponseBody为条件,然后分别调用HttpMessageConverter来进行消息的读写。
- SpringMVC 请求、响应流程
- springmvc httpclient 请求 响应
- WebxFrameworkFilter 请求响应流程
- Struts2请求响应流程
- SpringMVC请求处理流程
- SpringMVC请求流程说明
- springmvc请求流程
- SpringMVC 请求处理流程
- SpringMvc处理请求流程
- springMVC请求流程详解
- SpringMVC处理请求流程
- SpringMVC请求处理流程
- SpringMVC处理请求流程
- SpringMVC请求流程
- SpringMVC处理请求流程
- SpringMVC请求流程
- SpringMvc处理请求流程
- springmvc 请求响应时报异常
- fedora20 pci8311驱动移植
- Android GreenDao3.2配置及使用详解
- 逆向工程_Java
- MyBatis中#{}和${}的区别
- A push到B, B present到C时销毁B
- SpringMVC 请求、响应流程
- Java 引用 WeakReference
- Java Web发送邮件(注册或某些验证)
- Java 文件操作的学习(不断更新中)
- 序列化和反序列化
- selenium的光标悬停
- maven学习1——maven主要内容和学习路线
- Python-pywinauto-打开绿金在线软件
- UVALive-6955