Introduction: @RequestBody
Role:
i) This annotation is used to read the body portion of the request requests, parse using the httpmessageconverter of the system default configuration, and then bind the corresponding data to the object to be returned;
II) Then bind the object data returned by Httpmessageconverter to the parameters of the method in the controller.
Use time:
A) GET, post method, according to the request header Content-type value to determine:
- application/x-www-form-urlencoded, Optional (that is, not necessary, because the data of this situation @requestparam, @ModelAttribute can also be processed, of course @requestbody can also handle);
- Multipart/form-data, cannot be processed (i.e. using @requestbody cannot process data in this format);
- Other formats must be (other formats include Application/json, Application/xml, etc.). Data in these formats must be handled using @requestbody);
B) When put is submitted, it is judged according to the value of the request header Content-type:
- Application/x-www-form-urlencoded, must;
- Multipart/form-data, unable to deal with;
- Other formats, must;
Description: The data encoding format of the body part of request is specified by the Content-type of the header section;
@ResponseBody
Role:
The annotation is used to write the object returned by the controller's method to the body data area of the response object after the appropriate httpmessageconverter is converted to the specified format.
Use time:
The returned data is not a page of HTML tags, but is used in some other form of data (JSON, XML, etc.);
Httpmessageconverter
/*** Strategy interface that specifies a converter so can convert from and to HTTP requests and responses. * * @authorArjen Poutsma *@authorJuergen Hoeller *@since3.0*/ Public InterfaceHttpmessageconverter<t> { /*** Indicates whether the given class can is read by this converter. * @paramClazz the class to test for readability *@parammediatype the media type to read, can is {@codeNULL} if not specified. * Typically the value of a {@codeContent-type} header. * @return {@codetrue} if readable; {@codefalse} otherwise*/ BooleanCanRead (class<?>Clazz, mediatype mediatype); /*** Indicates whether the given class can is written by this converter. * @paramClazz the class to test for writability *@parammediatype the media type to write, can is {@codeNULL} if not specified. * Typically the value of an {@codeAccept} header. * @return {@codetrue} if writable; {@codefalse} otherwise*/ BooleanCanWrite (class<?>Clazz, mediatype mediatype); /*** Return the list of {@linkmediatype} objects supported by this converter. * @returnThe list of supported media types*/List<MediaType>getsupportedmediatypes (); /*** Read An object of the given type form the given input message, and returns it. * @paramClazz The type of object to return. This type must has previously been passed to the * {@link#canRead CanRead} method of this interface, which must has returned {@codetrue}. * @paraminputmessage The HTTP input message to read from *@returnThe converted Object *@throwsIOException in case of I/O errors *@throwsHttpmessagenotreadableexception in case of conversion errors*/T Read (Class<?extendsT>Clazz, Httpinputmessage inputmessage)throwsIOException, httpmessagenotreadableexception; /*** Write an given object to the given output message. * @paramt the object to write to the output message. The type of this object must has previously been * passed to the {@link#canWrite CanWrite} method of this interface, which must has returned {@codetrue}. * @paramcontentType The content type to use when writing. May is {@codenull} to indicate this * default content type of the converter must be used. If not {@codenull}, this media type must has * previously been passed to the {@link#canWrite CanWrite} method of this interface, which must has * returned {@codetrue}. * @paramoutputmessage the message to write to *@throwsIOException in case of I/O errors *@throwsHttpmessagenotwritableexception in case of conversion errors*/ voidWrite (T T, mediatype ContentType, Httpoutputmessage Outputmessage)throwsIOException, httpmessagenotwritableexception; }
The interface defines four methods, namely, CanRead (), read (), and CanWrite (), write () methods when reading data.
When using the <mvc:annotation-driven/> label configuration, the default configuration isRequestMappingHandlerAdapter(注意是RequestMappingHandlerAdapter
不是AnnotationMethodHandlerAdapter,详情查看Spring 3.1 document “16.14 Configuring Spring MVC”章节),并为他配置了一下默认的HttpMessageConverter:
Bytearrayhttpmessageconverter convertsbytearrays. Stringhttpmessageconverter converts strings. Resourcehttpmessageconverter converts to/from Org.springframework.core.io.Resource forAll media types. Sourcehttpmessageconverter converts to/From a javax.xml.transform.Source. Formhttpmessageconverter converts form data to/from a multivaluemap<string, string>. Jaxb2rootelementhttpmessageconverter converts Java objects to/from xml-addedifJAXB2 is present on the classpath. Mappingjacksonhttpmessageconverter converts to/from json-addedifJackson is present on the classpath. Atomfeedhttpmessageconverter converts Atom feeds-addedifRome is present on the classpath. Rsschannelhttpmessageconverter converts RSS feeds-addedifRome is present on the classpath.
ByteArrayHttpMessageConverter: 负责读取二进制格式的数据和写出二进制格式的数据;
StringHttpMessageConverter: 负责读取字符串格式的数据和写出二进制格式的数据;
Resourcehttpmessageconverter: Responsible for reading resource files and writing out resource file data;
Formhttpmessageconverter: Responsible for reading the form submitted data (can read the data format is application/x-www-form-urlencoded, can not read Multipart/form-data format data) ; Responsible for writing data in application/x-www-from-urlencoded and multipart/form-data formats;
Mappingjacksonhttpmessageconverter: Responsible for reading and writing data in JSON format;
Soucehttpmessageconverter: Responsible for reading and writing Javax.xml.transform.Source defined data in XML;
Jaxb2rootelementhttpmessageconverter: The data that is responsible for reading and writing XML tag format;
Atomfeedhttpmessageconverter: Responsible for reading and writing data in atom format;
Rsschannelhttpmessageconverter: Responsible for reading and writing data in RSS format;
当使用@RequestBody和@ResponseBody注解时,RequestMappingHandlerAdapter
就使用它们来进行读取或者写入相应格式的数据。
Httpmessageconverter Matching process:
When @RequestBody annotation: According to the Content-type type of the header part of the request object, each match the appropriate httpmessageconverter to read the data;
The Spring 3.1 source code is as follows:
PrivateObject readwithmessageconverters (methodparameter methodparam, Httpinputmessage inputmessage, Class paramTy PE)throwsException {mediatype ContentType=inputmessage.getheaders (). getContentType (); if(ContentType = =NULL) {StringBuilder builder=NewStringBuilder (Classutils.getshortname (Methodparam.getparametertype ())); String paramname=Methodparam.getparametername (); if(ParamName! =NULL) {builder.append (‘ ‘); Builder.append (paramname); } Throw NewHttpmediatypenotsupportedexception ("Cannot extract parameter (" + builder.tostring () + "): No Content-type found"); } List<MediaType> allsupportedmediatypes =NewArraylist<mediatype>(); if( This. messageconverters! =NULL) { for(httpmessageconverter<?> Messageconverter: This. Messageconverters) {Allsupportedmediatypes.addall (Messageconverter.getsupportedmediatypes ()); if(Messageconverter.canread (Paramtype, ContentType)) {if(logger.isdebugenabled ()) {Logger.debug ("Reading [" + paramtype.getname () + "] as \" "+ ContentType +" \ "using [" + Messageconvert ER + "]"); } returnMessageconverter.read (Paramtype, inputmessage); } } } Throw Newhttpmediatypenotsupportedexception (ContentType, allsupportedmediatypes); }
@ResponseBody Annotations: According to the Request Object Header section of the Accept attribute (comma-delimited), according to the type of accept, to traverse to find the httpmessageconverter can be processed;
The source code is as follows:
Private voidwritewithmessageconverters (Object returnvalue, Httpinputmessage inputmessage, Httpoutputmessage outputMess Age)throwsIOException, httpmediatypenotacceptableexception {List<MediaType> acceptedmediatypes =inputmessage.getheaders (). Getaccept (); if(Acceptedmediatypes.isempty ()) {Acceptedmediatypes=collections.singletonlist (Mediatype.all); } mediatype.sortbyqualityvalue (Acceptedmediatypes); Class<?> Returnvaluetype =Returnvalue.getclass (); List<MediaType> allsupportedmediatypes =NewArraylist<mediatype>(); if(Getmessageconverters ()! =NULL) { for(mediatype acceptedmediatype:acceptedmediatypes) { for(Httpmessageconverter messageconverter:getmessageconverters ()) {if(Messageconverter.canwrite (Returnvaluetype, Acceptedmediatype)) {Messageconverter.write (retur Nvalue, Acceptedmediatype, outputmessage); if(logger.isdebugenabled ()) {mediatype ContentType=outputmessage.getheaders (). getContentType (); if(ContentType = =NULL) {ContentType=Acceptedmediatype; } logger.debug ("Written [" + ReturnValue + "] as \" "+ ContentType +" \ "using [" + Messageconverter + "]"); } This. responseargumentused =true; return; } } } for(Httpmessageconverter messageconverter:messageconverters) {Allsupportedmediatypes.addall (messageCon Verter.getsupportedmediatypes ()); } } Throw Newhttpmediatypenotacceptableexception (allsupportedmediatypes); }
Add:
Mappingjacksonhttpmessageconverter called the Objectmapper.writevalue (OutputStream stream, Object) method, Objects returned using the @responsebody annotation are passed into the object parameter. If the returned object is a JSON string that has been formatted well, do not use @requestbody annotations, but should do so:
1, Response.setcontenttype ("Application/json; Charset=utf-8 ");
2, Response.getwriter (). print (JSONSTR);
Output directly to the body area, then the view is void.
This article transferred from: http://blog.csdn.net/kobejayandy/article/details/12690555
The @requestbody of Spring MVC, @ResponseBody detailed