搭建SSM框架SpringMVC之JSON傳數據


json格式的字符串(傳遞數據的一種載體)
json格式字符串 <----> js對象
  js中的JSON類型
    JSON.stringify(obj);
    JSON.parse(str);
json格式字符串 <----> java對象
  使用第三方jar來完成即可

例子:

  ajex請求給服務器發送JSON格式字符串,服務器接受,利用第三方jar把JSON格式字符串轉換成對象,然后返回JSON格式字符串,js接受,jQuery自動把它轉換成js對象
拿到的都是對象,但傳輸的都是字符串(JSON格式)

 測試頁面1(json1.jsp):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath %>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>json1.jsp</title>
<script type="text/javascript">
    
    //js對象
    var obj = {id:1,name:"tom1",age:21};
    console.log(obj);
    console.log(obj.id);
    console.log(obj.name);
    console.log(obj.age);
    
    //json格式的字符串
    var jsonStr = JSON.stringify(obj);
    //把js對象轉為json格式字符串
    //{"id":1,"name":"tom1","age":21}
    console.log(jsonStr);
    
    console.log("---------------------------");
    
    //json格式字符串
    jsonStr = '{"id":2,"name":"tom2","age":22}';
    console.log(jsonStr);
    
    //json格式字符串轉換為js對象
    obj = JSON.parse(jsonStr);
    console.log(obj);

</script>
</head>
<body>
    <h1>json1.jsp</h1>
    <hr>
    
    
    

</body>
</html>

測試頁面2(json2.jsp):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath %>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>json2.jsp</title>
<script type="text/javascript" src="static/js/jquery/jquery-1.8.3.min.js"></script>

<script type="text/javascript">
    
    $(function(){
        
        $("#btn1").on("click",function(){
            
            var obj = {id:1,name:"tom",age:20};
            var jsonStr = JSON.stringify(obj);
            
            /*
                contentType屬性表示本次請求給服務器發送的數據類型是什么
                    對應了之前請求頭中的屬性:Content-Type
                dataType屬性表示本次請求希望服務器返回的數據類型是什么
                    對應了之前請求頭中的屬性:Accept
            */
            
            
            $.ajax({
                type: "POST",
                url: "request_body/test2",
                contentType: "application/json",
                data: jsonStr,
                dataType: "text",
                success: function(msg){
                    console.log(msg);
                }
            });
            
        });
        
        
        
        $("#btn2").on("click",function(){
            var obj = {id:1,name:"tom",age:20};
            var jsonStr = JSON.stringify(obj);
            
            
            /*
            contentType屬性表示本次請求給服務器發送的數據類型是什么
                對應了之前請求頭中的屬性:Content-Type
            dataType屬性表示本次請求希望服務器返回的數據類型是什么
                對應了之前請求頭中的屬性:Accept
            */
            $.ajax({
                type: "POST",
                url: "request_body/test3",
                contentType: "application/json",
                data: jsonStr,
                dataType: "json",
                success: function(obj){
                    //jquery會把json格式字符串自動轉為js對象
                    console.log(obj);
                    console.log(obj.msg);
                }
            });
            
        });
        
        
        
        $("#btn4").on("click",function(){
            var obj = {id:1,name:"tom",age:20};
            var jsonStr = JSON.stringify(obj);
            
            
            /*
            contentType屬性表示本次請求給服務器發送的數據類型是什么
                對應了之前請求頭中的屬性:Content-Type
            dataType屬性表示本次請求希望服務器返回的數據類型是什么
                對應了之前請求頭中的屬性:Accept
            */
            $.ajax({
                type: "POST",
                url: "request_body/test4",
                contentType: "application/json",
                data: jsonStr,
                dataType: "json",
                success: function(obj){
                    //jquery會把json格式字符串自動轉為js對象
                    console.log(obj);
                    console.log(obj.msg);
                }
            });
            
        });
        
        
        $("#btn5").on("click",function(){
            var obj = {id:1,name:"tom",age:20};
            var jsonStr = JSON.stringify(obj);
            
            
            /*
            contentType屬性表示本次請求給服務器發送的數據類型是什么
                對應了之前請求頭中的屬性:Content-Type
            dataType屬性表示本次請求希望服務器返回的數據類型是什么
                對應了之前請求頭中的屬性:Accept
            */
            $.ajax({
                type: "POST",
                url: "request_body/test5",
                contentType: "application/json",
                data: jsonStr,
                dataType: "json",
                success: function(obj){
                    //jquery會把json格式字符串自動轉為js對象
                    console.log(obj);
                    console.log(obj.id);
                    console.log(obj.name);
                    console.log(obj.age);
                    console.log(obj.dob);
                }
            });
            
        });
        
        
    });
    
</script>
</head>
<body>
    <h1>json2.jsp</h1>
    <hr>
    
    <input id="btn1" type="button" value="按鈕1">
    <input id="btn2" type="button" value="按鈕2">
    <input id="btn4" type="button" value="按鈕4">
    <input id="btn5" type="button" value="按鈕5">
    

</body>
</html>

后台的控制類:

package com.briup.web.annotation;

import java.io.Writer;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.briup.bean.User;

@RequestMapping("/request_body")
@Controller
public class RequestBodyController {
    
    /*
     * @RequestBody注解的使用
     * 作用:獲得請求體中的內容
     */
    
    
    @RequestMapping("/test1")
    public String test1(@RequestBody String str)throws Exception{
        System.out.println("RequestBodyController test1..");
        
        //id=1&name=tom&age=20
        System.out.println("str = "+str);
        
        return "test";
    }
    
    
    //@RequestBody注解一般結合ajax,然后以json格式字符串進行傳值
    //因為正常情況下,使用@RequestBody注解獲得了表單中的值:id=1&name=tom&age=20
    //這個值id=1&name=tom&age=20,我們獲取后作用不大
    //但是如果從請求體中獲得一個json格式的字符串,那就不一樣了
    //因為可以容易的把json格式字符串轉換為java的對象
    //需要引入第三方jar包,才可以把json字符串轉為java對象
    @RequestMapping("/test2")
    public void test2(@RequestBody User u,Writer out)throws Exception{
        System.out.println("RequestBodyController test2..");
        
        System.out.println("u = "+u);
        
        out.write("hello");
        out.flush();
        
    }
    
    
    //給ajax請求返回json格式的字符串
    @RequestMapping("/test3")
    public void test3(@RequestBody User u,Writer out)throws Exception{
        System.out.println("RequestBodyController test3..");
        
        System.out.println("u = "+u);
        
        String jsonStr = "{\"msg\":\"hello world\"}";
        
        out.write(jsonStr);
        
        out.flush();
        
    }
    
    
    //@ResponseBody表示把方法的返回值放到響應體中
    @ResponseBody
    @RequestMapping("/test4")
    public String test4(@RequestBody User u)throws Exception{
        System.out.println("RequestBodyController test4..");
        
        System.out.println("u = "+u);
        
        String jsonStr = "{\"msg\":\"hello world\"}";
        
        return jsonStr;
    }
    
    @ResponseBody
    @RequestMapping("/test5")
    public User test5(@RequestBody User u)throws Exception{
        System.out.println("RequestBodyController test5..");
        
        System.out.println("u = "+u);
        
        //對象會被自動轉為json格式字符串
        User user = new User(2L,"tom2",32);
        
        return user;
    }
    
    
}

總結:

@RequestBody注解
可以接收客戶端ajax請求中的json數據並且轉換為對象,但是只能接收post請求中的數據,因為post請求的數據在請求體中(request-body).
需要引入操作json的相關jar包:
  jackson-core-2.8.5.jar
  jackson-annotations-2.8.5.jar
  jackson-databind-2.8.5.jar
或者
  jackson-mapper-asl-1.9.13.jar
  jackson-core-asl-1.9.13.jar

 

客戶端使用ajax發送json數據給Controller,Controller里面接收json數據並且轉換為對象
1.ajax請求發送的時候要指定為post方式
2.ajax請求發送的時候要指定contentType:"application/json"
3.ajax請求發送的時候要把json對象轉換為字符串再發送
4.Controller中要使用@RequestBody指定接收數據的參數
5.項目中要引入json相關的jar包
6.如果此ajax請求還希望Controller返回的數據也是json格式的,那么需要在發送ajax請求的時候指定dataType:"json",
7.Controller中的方法要返回json格式的數據給客戶端,可以使用@ResponseBody標簽 或者 在方法中自己使用response對象獲得io流給客戶端寫回去

注意:
ajax發送請求的時候,請求頭中的Content-Type默認值是: application/x-www-form-urlencoded,表示當前請求中如果有數據的話,將會是key=value&key=value的形式

注意:在javascript中,json對象和字符串之間的轉換:
  JSON.stringify(obj)將JSON對象轉為字符串。
  JSON.parse(string) 將字符串轉為JSON對象;

 


免責聲明!

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



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