@ RequestBody in springMVC
Recently, it's okay to help students build a graduation project using SpringMVC. Project development has been useful but has never been built on their own. Many problems have arisen in the use of @ Request.
@ RequestBodyConvert the HTTP Request body to an appropriate HttpMessageConverter object.
@ ResponseBodyReturn the content or object as the HTTP response body, and call the Adapter conversion object suitable for HttpMessageConverter to write it to the output stream.
First, springMVC configuration file:
Ii. spring. jar + jackson. jar
Main needsSpring-webmvc,Jackson-mapper-aslTwo packages.Log4jView logs
3. But the program keeps reporting errors such as 400/415 when processing ajax requests.
$. Ajax ({
Type: POST,
Url: $ {pageContext. request. contextPath}/login,
DataType: json,
ContentType: application/json,
Data: JSON. stringify (param ),
Success: function (data ){
Console.info (data );
}
});
After reading many articles on the internet, I found that:
@ RequestBody receives a Json object, which has never been successfully debugged. Later, it was found that @ RequestBody actually receives a Json object string instead of a Json object. However, ajax requests often contain Json objects. Later, we found that the objects can be converted into strings by using JSON. stringify (data. In addition, you must specify dataType: json, contentType: application/json during ajax requests so that you can easily upload an object or List to the Java end.
4. At this point, you can proceed normally on the control side:
@ RequestMapping (value =/login, method = RequestMethod. POST)
@ ResponseBody
Public ResultDTO login (@ RequestBody UserMessage user ){
ResultDTO dto = ResultDTO. getIntance ();
Return dto;
}