首页 > 编程语言 > 详细

SpringMVC @RequestBody接收Json对象字符串 demo

时间:2016-12-23 18:50:42      阅读:283      评论:0      收藏:0      [点我收藏+]

springmvc 的这个 @RequestBody 用得比较少,今天看了一下,还是很方便.

 @RequestBody 接收类似 [{name: "test"}, {name: "张三"}] 这样的json字符串.

 

先看页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">  
     function test(){
            var saveDataAry=[];  
            var data1={"name":"test"};  
            var data2={"name":"张三"};  
            saveDataAry.push(data1);  
            saveDataAry.push(data2);         
            $.ajax({ 
                type:"POST", 
                url:"http://localhost/test/student", 
                dataType:"json",      
                contentType:"application/json",               
                data:JSON.stringify(saveDataAry), 
                success:function(data){ 
                   alert(data)                   
                } 
             }); 
      }
</script>
</head>
<body>
    <input type="button" onclick="test()" value="测试">
</body>
</html>

 

最后看后台代码:

import java.util.List;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {

    @ResponseBody
    @RequestMapping(value="/student",method=RequestMethod.POST)
    public String student(@RequestBody List<Student> students ){
        for(Student s : students){
            System.out.println("学生姓名:"+s.getName());
        }
        return "ok";
    }
}

class Student{
    
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    
}

 

小结一下,这样传参数就是json字符串化.

 

SpringMVC @RequestBody接收Json对象字符串 demo

原文:http://www.cnblogs.com/huzi007/p/6215639.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!