@RequestBody, explanation of @ResponseBody annotations (GO)

Source: Internet
Author: User

@responsebody indicates that the return result of the method is written directly to the HTTP response body
Generally used when retrieving data asynchronously, after using @requestmapping, the return value is usually resolved to the jump path, plus @responsebody returns the result will not be resolved to the jump path, but directly to the HTTP response body. For example, asynchronously fetching JSON data, plus @responsebody, will return the JSON data directly.

Introduction:

After an article on how to deal with the @requestmapping method parameter binding, detailed introduction of the next @requestbody, the use of the @ResponseBody and the timing of usage, but also for some of the articles described in a previous article to clarify some of the parts (Article address: http ://www.byywee.com/page/m0/s702/702424.html).

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
<span style= "Font-family:microsoft Yahei;" >/*** Strategy interface that specifies a converter so can convert from and to HTTP requests and responses. * *@authorArjen Poutsma *@authorJuergen Hoeller *@since3.0*/PublicInterface httpmessageconverter<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*/Boolean CanRead (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*/Boolean CanWrite (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<?Extends t>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 { @code  @param  Outputmessage the message to write to *  @throws Span style= "color: #008000;" > IOException in case of I/O errors *  @throws */void write (T T, mediatype ContentType, Httpoutputmessage outputmessage) throws IOException, httpmessagenotwritableexception;} </span>              

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.ResourceFor all media types.    Sourcehttpmessageconverter converts To/from a javax.xml.transform.Source. Formhttpmessageconverter converts form data to/from a multivaluemap<string, string> if JAXB2 is present on the classpath. Mappingjacksonhttpmessageconverter converts to/from json-added if Jackson is present on the classpath. Atomfeedhttpmessageconverter converts Atom feeds-added if  Rome is present on the classpath. Rsschannelhttpmessageconverter converts RSS feeds-added if Rome is present on the Classpat H.          

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 paramType)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); }ThrowNewHttpmediatypenotsupportedexception ("Cannot extract parameter (" + builder.tostring () + "): No Content-type found"); } list<mediatype> allsupportedmediatypes =New arraylist<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 ["+ Messageconverter +"] ");} return messageconverter.read (Paramtype, inputmessage);}} } throw new httpmediatypenotsupportedexception (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:

PrivatevoidWritewithmessageconverters (Object returnvalue, Httpinputmessage inputmessage, Httpoutputmessage OutputMessa GeThrowsIOException, 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 =New arraylist<mediatype>();if (getmessageconverters ()! =Null) {For(mediatype acceptedmediatype:acceptedmediatypes) {For(Httpmessageconverter messageconverter:getmessageconverters ()) {If(Messageconverter.canwrite (Returnvaluetype, Acceptedmediatype)) {Messageconverter.write (returnvalue, 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; returnfor (Httpmessageconverter messageconverter: Messageconverters) {Allsupportedmediatypes.addall (Messageconverter.getsupportedmediatypes ());}} throw new
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.

Resources:

1. Spring 3.1 Doc:

Spring-3.1.0/docs/spring-framework-reference/html/mvc.html

2, Spring 3.x MVC Primer 4--@responsebody & @requestbody

Http://www.byywee.com/page/M0/S702/702424.html

@RequestBody, explanation of @ResponseBody annotations (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.