First, when you use the SSM framework for Web development, you often encounter the @requestmapping, @ResponseBody, and @requestbody three parameters in the CTRL layer. Bloggers on their own in the project development summed up some of the knowledge points about the delicate relationship between the three.
[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:
1 @Controller2 //set the parent path you want to jump to3@RequestMapping (value ="/controllers")4 Public classStatisticuserctrl {5 //If you need to inject, write the class that needs to be injected6 //@Autowired7 8 //the sub-path under the Set method9@RequestMapping (value ="/method")Ten PublicString HelloWorld () { One A return "HelloWorld"; - - } the}
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:
1 function Login () {2 varURL ="${pagecontext.request.contextpath}/person/login/";3 varQuery = $ ('#id'). Val () +'/'+ $('#name'). Val () +'/'+ $('#status'). Val ();4URL + =query;5$.Get(URL, function (data) {6Alert"ID:"+ Data.id +"Name:"+ Data.name +"Status:"7+data.status);8 });9}
For example:
1 /**2 * {id}/{name}/{status} in @RequestMapping (value = "User/login/{id}/{name}/{status}")3 * with @PathVariable int ID, @PathVariable String name, @PathVariable boolean status4 * One by one corresponds, matches by name. 5 */6 7@RequestMapping (value ="User/login/{id}/{name}/{status}")8 @ResponseBody9 //data types are available under @PathVariable annotationsTen PublicUser Login (@PathVariableintID, @PathVariable String name, @PathVariable boolean status) { One //returns a user object in response to an AJAX request A return NewUser (ID, name, status); -}@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:
1 function Login () {2 varDatas ='{"username": "'+ $('#username'). Val () +'" ," userid ":"'+ $('#userid'). Val () +'"," status ":"'+ $('#status'). Val () +'"}';3 $.ajax ({4Type:'POST',5ContentType:'Application/json',6Url:"${pagecontext.request.contextpath}/user/login",7ProcessData:false,8DataType:'JSON',9 Data:datas,Ten success:function (data) { OneAlert"userid:"+ Data.userid +"Username:"+ Data.username +"Status:"+data.status); A }, - error:function (XMLHttpRequest, Textstatus, Errorthrown) { -Alert"An exception occurred, exception information:"+textstatus,"Error"); the } - }); -};
For example:
1@RequestMapping (value ="User/login")2 @ResponseBody3 //writes a request made by Ajax (Datas) to the User object, returning the JSON object response back4 PublicUser Login (user user) {5User User =NewUser ();6User. Setuserid (1);7User. Setusername ("MrF");8User. SetStatus ("1");9 returnuser;Ten}
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:
12) 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-Datacannot be processed (that is, using @requestbody cannot process this format); Other formats must be (other formats include application/json, application/ XML, and so on. 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:
" User/login " ) @ResponseBody// writes the request made by Ajax (Datas) to the user object in public User Login (@RequestBody User user) { // This will no longer be resolved to a jump path, but rather the user object is written directly to the HTTP response body in return User; }
Finally thank Walkerjong Spring Source Support, if you have any questions please comment, your proposal is my growth path essential nutrients, or that sentence, we will not only new!
On the usage and difference of @requestmapping @ResponseBody and @RequestBody annotations