Description of Spring MVC common annotations

Source: Internet
Author: User
Tags addall html tags

recently studied springboot, so familiarize yourself with the annotations commonly used in MVC, so that you can easily develop

Brief introduction:

@RequestMapping

Requestmapping is an annotation that handles request address mappings and can be used on classes or methods. On a class, the method that represents all response requests in a class is the parent path of the address.

The requestmapping annotation has six properties, and we'll describe her in three categories below.

1, value, method;

Value: Specifies the actual address of the request, the specified address can be the URI Template mode (which will be explained later);

Method: Specifies the type of method requested, GET, POST, PUT, delete, and so on;

2, Consumes,produces;

Consumes: Specifies the type of submission to process the request (Content-type), such as Application/json, text/html;

Produces: Specifies the type of content returned, only if the specified type is included in the (Accept) type in the request header;

3, Params,headers;

Params: Specifies that some parameter values must be included in the request before the method is processed.

Headers: Specifies that certain header values must be included in the request in order for the method to process requests.

Example: 1, value/method example

Default Requestmapping ("...") that is value;

1 @Controller2@RequestMapping ("/appointments")3  Public classAppointmentscontroller {4 5     PrivateAppointmentBook AppointmentBook;6     7 @Autowired8      PublicAppointmentscontroller (AppointmentBook appointmentbook) {9          This. AppointmentBook =AppointmentBook;Ten     } One  A@RequestMapping (method =requestmethod.get) -      PublicMap<string, appointment>get () { -         returnAppointmentbook.getappointmentsfortoday (); the     } -  -@RequestMapping (value= "/{day}", method =requestmethod.get) -      PublicMap<string, appointment> getforday (@PathVariable @DateTimeFormat (iso=ISO. Date) (Date day, model model) { +         returnAppointmentbook.getappointmentsforday (day); -     } +  A@RequestMapping (value= "/new", method =requestmethod.get) at      Publicappointmentform Getnewform () { -         return Newappointmentform (); -     } -  -@RequestMapping (method =requestmethod.post) -      PublicString Add (@Valid appointmentform appointment, bindingresult result) { in         if(Result.haserrors ()) { -             return"Appointments/new"; to         } + appointmentbook.addappointment (appointment); -         return"Redirect:/appointments"; the     } *}

The URI value of value is the following three categories:

A) can be specified as a normal specific value;

B) can be specified as a class of values containing a variable (URI Template Patterns with Path Variables);

C) can be specified as a class of values with regular expressions (URI Template Patterns with Regular Expressions);

Example B)

@RequestMapping (value= "/owners/{ownerid}", method=requestmethod.get) public String findowner (@PathVariable string ownerID, model model) {  owner owner = ownerservice.findowner (ownerid);    Model.addattribute ("owner", owner);    return "Displayowner"; }

Example C)

@RequestMapping ("/spring-web/{symbolicname:[a-z-]+}-{version:\d\.\d\.\d}.{ Extension:\. [A-Z]} ")  public void handle (@PathVariable string version, @PathVariable string extension) {        //...  }}
2 consumes, produces example

Examples of Cousumes:

@Controller @requestmapping (value = "/pets", method = Requestmethod.post, consumes= "Application/json") public void Addpet (@RequestBody Pet Pet, model model) {        //implementation omitted}

The Content-type method only processes requests with the request "Application/json" type.

Examples of produces:

@Controller @requestmapping (value = "/pets/{petid}", method = Requestmethod.get, produces= "Application/json") @ Responsebodypublic Pet Getpet (@PathVariable String Petid, model model) {        //implementation omitted}

The Application/json method only handles requests in the request that accept headers contain "a", and implies that the returned content type is Application/json;

3 Params, headers example

Examples of params:

@Controller @requestmapping ("/owners/{ownerid}") public class Relativepathuritemplatecontroller {  @ Requestmapping (value = "/pets/{petid}", method = Requestmethod.get, params= "Myparam=myvalue") public  void Findpet ( @PathVariable string ownerid, @PathVariable string petid, model model) {        //implementation omitted  }}

A request with a value of "myvalue" named "Myparam" is included in the processing request only;

Examples of headers:

@Controller @requestmapping ("/owners/{ownerid}") public class Relativepathuritemplatecontroller {@RequestMapping ( Value = "/pets", method = Requestmethod.get, headers= "referer=http://www.ifeng.com/") public  void Findpet (@ Pathvariable string ownerid, @PathVariable string petid, model model) {        //implementation omitted  }}
@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 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.

Description of Spring MVC common annotations

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.