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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM