On the usage and difference of @requestmapping @ResponseBody and @RequestBody annotations

Source: Internet
Author: User

[Email protected]

International practice first describes what is @requestmapping, @RequestMapping is an annotation to handle the request address mapping, which 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, and on the method, the address in the annotation that is appended to the method under the parent path of the class is accessed by the method, where it is important to note that @requestmapping is useless on the class, but must be used on the method.

For example:

 @Controller  Set the parent path you want to jump @requestmapping (value =  "/controllers") public class Statisticuserctrl {//if required , then write the class //@Autowired //set method to the sub-path @RequestMapping (value =  "/method") public string helloworld () {return  "HelloWorld";}}  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

Its principle is also very good to understand, its corresponding action is "(Parent path) controller/(parent Path) method". Therefore, accessing the method Http://localhost:8080/controller/method on the local server will return (jump) to the "helloworld.jsp" page.

Speaking of which, by the way @PathVariable annotations, which are used to get the dynamic parameters in the request path (URL).

Page to make a request:

function login () {var url = var query = $ ( ' #id '). Val () +  '/' + $ ( #name '). Val () +  '/' + $ ( ' #status '). val (); URL + = Query $.get (URL, function (data) { Alert ( "ID:" + data.id +  "name:" + data.name +             
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

For example:

/*** @RequestMapping {id}/{name}/{status}* and  @RequestMapping (value =  "user/login/{id}/{name}/{ Status} ")  @ResponseBody //@PathVariable annotations are available in the data type public User login (@PathVariable int ID, @ Pathvariable String name, @PathVariable boolean status) {// Returns a user object in response to an AJAX request return new User (ID, name, status);}  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
@ResponseBody

The @Responsebody annotation indicates that the returned result of the method is written directly to the HTTP response Body (responsebody), which is generally used when fetching data asynchronously, usually after the use of a @RequestMapping, the return value usually resolves to a jump path, plus @ After Responsebody, the returned results are not resolved to the jump path, but are written directly to the HTTP response body.
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.);

When the page makes an asynchronous request:

functionLogin() {var datas =' {' username ': ' ' + $ (' #username '). Val () +' "," userid ":" ' + $ (' #userid '). Val () +' "," status ":" ' + $ (' #status '). Val () + ' POST ', ContentType:  ' Application/json ', url: Span class= "hljs-string" > "${pagecontext.request.contextpath}/user/login", ProcessData: false, DataType:  ' json ', Data:datas, success: function "username:" + data.username + function< Span class= "Hljs-params" > (XMLHttpRequest, Textstatus, Errorthrown) {alert ( "error"); } });}; 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

For example:

@RequestMapping(value = "user/login")@ResponseBody// 将ajax(datas)发出的请求写入 User 对象中,返回json对象响应回去public User login(User user) { User user = new User(); user .setUserid(1); user .setUsername("MrF"); user .setStatus("1"); return user ;}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

Asynchronously gets the JSON data, plus @Responsebody annotations, and returns the JSON data directly.

@RequestBody

The @RequestBody annotation is to insert the HTTP request body into the method, using the appropriate httpmessageconverter to write the request body to an object.

Role:

1) 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;
2) 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, cannot handle; other formats, must;

Description: The data encoding format of the body part of request is specified by the Content-type of the header section;

For example:

@RequestMapping(value = "user/login")@ResponseBody// 将ajax(datas)发出的请求写入 User 对象中public User login(@RequestBody User user) { // 这样就不会再被解析为跳转路径,而是直接将user对象写入 HTTP 响应正文中 return user; }

On the usage and difference of @requestmapping @ResponseBody and @RequestBody 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.