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

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" οnclick="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字符串化.

 

转载于:https://www.cnblogs.com/huzi007/p/6215639.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值