Spring Boot 中,Json 数据传值方式
3,492 total views, 3 views today
之前整理过一篇 Spring MVC 中的传值方式。《Spring MVC 传值方式总结》
介绍了多种传值方式,Spring Boot 本质上就是一个配置好的 Spring MVC,所以能够全盘通用。
这里再举例一下,最常用的传递 Json 数据的方式,前端传递到 Controller,以及 Controller 传递到前端。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
@Controller public class Index { @PostMapping("/accept") @ResponseBody public Map<String, String> Accept(@RequestBody User user) { Map<String, String> map = new HashMap<String, String>(); map.put("username", user.firstname+" "+user.lastname); return map; } } class User { String firstname; String lastname; public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } } |
前端代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script> <script> $(function() { var person={firstname:"Bill", lastname:"Gates"}; var options = { type : 'post', url : "/accept", data: JSON.stringify(person),//取得person对象的string contentType: 'application/json', success : function(result) { alert(result.username); } }; $("#btn1").click(function() { $.ajax(options); }); }); </script> </head> <body> <input type="button" id="btn1" value="test" /> </body> </html> |
代码说明:
Controller 端,参数 User 类,必须和前端传来的 json 串结构相同,能够稳定的反序列化,不然会接收不到正确的值。@RequestBody 注解意味着需要将前端传来的 json 串转成 User 类,必须要有这个注解。同理@ResponseBody 注解,将 Controller 中返回的类型序列化成 Json 格式,返回到前端。
前端 jquery 代码,注意传输的类型必须是 contentType: ‘application/json’, 并且传输的 data 是一个 json 数据的字符串,并且和接收端的格式是一致的,不然会出错。提交成功后的返回值,是一个 json 对象,可以直接读取这个 json 对象的值。
原创文章,转载请注明出处!http://www.javathings.top/spring-boot中,json数据传值方式/