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;
Ps:spring's @requestbody is very bull x, you can convert the submitted JSON directly to the Pojo object. Configuration:
The XML namespace of MVC needs to be added, otherwise the configuration cannot be resolved.
Xmlns:mvc= "Http://www.springframework.org/schema/mvc" xsi:schemalocation= "Http://www.springframework.org/schema /mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "
Added in xml: <mvc:annotation-driven/>
Automatic registration of defaultannotationhandlermapping and annotationmethodhandleradapter two beans
The Annotationmethodhandleradapter will initialize 7 converters, which can be called by calling Annotationmethodhandleradapter's Getmessageconverts () method to get a collection of converters list
Bytearrayhttpmessageconverter Stringhttpmessageconverter Resourcehttpmessageconverter SourceHttpMessageConverter Xmlawareformhttpmessageconverter Jaxb2rootelementhttpmessageconverter Mappingjacksonhttpmessageconverter
Parsing of JSON is done through the Mappingjacksonhttpmessageconverter converter.
Adding <mvc:annotation-driven/> is not enough, you will need to find the Jackson bag in the CLASSPATH environment to add maven dependencies:
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId> jackson-mapper-asl</artifactid> <version>1.9.8</version> <type>jar</type > <scope>compile</scope> </dependency>
@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 the can convert from and to HTTP requests and responses. * * @author Arjen Poutsma * @author Juergen Hoeller * @since 3.0 */public interface Httpmessageconverter<t> {/** * Indicates whether the given class can is read by this converter. * @param clazz the class to test for readability * @param mediatype the media type to read, can is {@code null} if not Specified. * Typically the value of a {@code Content-type} header. * @return {@code true} if readable; {@code false} otherwise */Boolean canRead (class<?> Clazz, mediatype mediatype); /** * Indicates whether the given class can be written by this converter. * @param clazz the class to test for writability * @param mediatype the media type to write, can is {@code null} if no T specified. * Typically the value of an {@code Accept} header. * @return {@code true} if writable;{@code false} otherwise */Boolean canWrite (class<?> Clazz, mediatype mediatype); /** * Return the list of {@link mediatype} objects supported by this converter. * @return The list of supported media types */list<mediatype> getsupportedmediatypes (); /** * Read An object of the given type form the given input message, and returns it. * @param clazz 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 {@code true}. * @param inputmessage the HTTP input message to read from * @return the converted Object * @throws IOException in Case of I/O errors * @throws httpmessagenotreadableexception in case of conversion errors */T read (class<? Extends T> clazz, Httpinputmessage inputmessage) throws IOException, httpmessagenotreadableexception; /** * Write an given object to the given output messagE. * @param t 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 have returned {@code true}. * @param contentType The content type to use when writing. May is {@code null} to indicate, the * default content type of the converter must be used. If not {@code null}, this media type must has * previously been passed to the {@link #canWrite canWrite} method of th is interface, which must has * returned {@code true}. * @param outputmessage the message to write to * @throws IOException in case of I/O errors * @throws Httpmessageno Twritableexception in case of conversion errors */void write (T T, mediatype ContentType, Httpoutputmessage OUTPUTM Essage) 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 converts byte arrays. Stringhttpmessageconverter converts strings. Resourcehttpmessageconverter converts To/from Org.springframework.core.io.Resource for all 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-added 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 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:
Private Object readwithmessageconverters (Methodparameter methodparam, Httpinputmessage inputmessage, Class paramType) Throws Exception {MediaType contentType = Inputmessage.getheaders (). getContentType (); if (ContentType = = null) {StringBuilder builder = new StringBuilder (Classutils.getshortname (methodparam.getpar Ametertype ())); String paramname = Methodparam.getparametername (); if (paramname! = null) {builder.append ('); Builder.append (paramname); } throw new Httpmediatypenotsupportedexception ("Cannot extract parameter (" + BUILDER.TOSTR ING () + "): no Content-type found"); } list<mediatype> allsupportedmediatypes = new arraylist<mediatype> (); if (this.messageconverters! = null) {for (httpmessageconverter<?> MessageConverter:this.messageConvert ERS) {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:
private void Writewithmessageconverters (Object returnvalue, Httpinputmessage inputmessage, Httpoutputmessag E outputmessage) throws IOException, 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 (). Getconten Ttype (); if (ContentType = = null) {ContentType = Acceptedmediatype; } logger.debug ("written [" + ReturnValue + "] as \" "+ ContentType + "\" Using ["+ Messageconverter +"] "); } this.responseargumentused = true; Return }}} for (Httpmessageconverter messageconverter:messageconverters) { Allsupportedmediatypes.addall (Messageconverter.getsupportedmediatypes ()); }} throw new HttpmediatypenotacceptableexCeption (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.
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)