The transfer jason SpringMVC ajax Detailed data and annotation @RequestBody and @ResonseBody

     A recent encounter in doing ajax user name check a number of issues, constantly in the process of debug also deepened my understanding of the springMVC the ajax data transfer jason, hope to need some help small partner -

Tools: IDEA 

We look through the code to understand:

1. Figure js code as follows: Because the user name is a check, the incoming data is only the user name;

The PS : SPRINGMVC passed by reference to the background when ajax: @RequestBody received as a string Json object, rather than a Json object. However, a request is often transmitted Json object ajax, you will be able to become the object string JSON.stringify (data) manner. While ajax request should specify the time dataType: "json", contentType: "application / json".

 The 2.controller achieve:

   We can find our incoming data only username Why RequestBody get is a POJO class of objects (of course this Admin class more than the property is) it? Then we need to have an understanding of the specific operation @RequestBody friends and @ResponseBody Both comments and SpringMVC in the ajax.

. ① First, a brief introduction Jackson : Jackson is a simple Java-based application library, Jackson can easily convert Java objects to json objects and xml documents, also can convert json, xml into Java objects; to introduce powerful Jackson needs we import its dependencies in pom.xml (configure the XML < MVC: Annotation-Driven /> ) 

Figure:

可以在外部库中看到:

 关于Jackson的详细用法大家可以参考这篇文章https://www.cnblogs.com/naaoveGIS/p/3893651.html

.@RequestBody:简单的说就是 RequestBody用于获取请求体的结构,使用了Jackson框架和@RequestBody注解后所以可以实现把请求体的内容封装到Admin对象中,同时Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配,自动为该对象填充属性值。

③.@ResponseBody:ResponseBody将返回的值直接写到Http的响应体中,不需要替换为Spring的Model或者解析为视图,相当于response.getWriter.write();当使用了Jackson框架和@ResponseBody注解之后,Jackson框架自动将对象解析成Json串返还数据给前端页面。

大家想详细了解@RequestBody和@ResponseBody的参考这篇文章:http://www.chinacion.cn/article/608.html

      因此我们传入的Jason数据由于我们添加了Jackson依赖后会被转换为Java对象,同时Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配,所以我们对POJO类的对象调用service层的方法啦~是不是觉得灰常强大灰常好用啊,嘻嘻小伙伴要是觉得有帮助的话欢迎顶一下哈~

 

Guess you like

Origin www.cnblogs.com/wyhhh/p/11279068.html