SpringMVC之@RequestBody

@RequestBody

因为一直觉得传简单对象直接不用注解也可以自动组装,就以为Spring可以为我们组装所有类型的对象。但今天测试过,原来象Map,List或复合对象都必需使用这个注解才可以正确组装,以下是我的测试代码:

首先写个测试的Controller:

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.cunframework.core.common.controller.BaseController;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

class A{
    private String name;
    private String value;
    public String getName() {
        return name;
    }
    public String getValue() {
        return value;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setValue(String value) {
        this.value = value;
    }
}

class B{
    private List<A> a;
    private String count;

    public List<A> getA() {
        return a;
    }
    public String getCount() {
        return count;
    }
    public void setA(List<A> a) {
        this.a = a;
    }
    public void setCount(String count) {
        this.count = count;
    }
}

@Scope("prototype")
@Controller
@RequestMapping("/rb")

public class RequestBodyController extends BaseController{

    @RequestMapping(value = "test1")
    @ResponseBody
    public Map test1(A a,HttpServletResponse response) {

        try {
            System.out.println(JSON.toJSONString(a));
            return toSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return toError();
        }
    }

    @RequestMapping(value = "test2")
    @ResponseBody
    public Map test2(List<A> a,HttpServletResponse response) {
        try {
            System.out.println(JSON.toJSONString(a));
            return toSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return toError();
        }
    }

    @RequestMapping(value = "test3")
    @ResponseBody
    public Map test3(@RequestBody List<A> a,HttpServletResponse response) {
        try {
            System.out.println(JSON.toJSONString(a));
            return toSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return toError();
        }
    }

    @RequestMapping(value = "test4")
    @ResponseBody
    public Map test4(B b,HttpServletResponse response) {
        try {
            System.out.println(JSON.toJSONString(b));
            return toSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return toError();
        }
    }

    @RequestMapping(value = "test5")
    @ResponseBody
    public Map test5(@RequestBody B b,HttpServletResponse response) {
        try {
            System.out.println(JSON.toJSONString(b));
            return toSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return toError();
        }
    }
}

测试用的html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
    <script>

        function ajax(url,data,contentType){
            $.ajax({
                type: "POST",
                contentType: contentType,
                url: url,
                data: data,
                success: function(data){
                    console.log(data);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error Occured!");
                }
            });
        }

        function test1(){
            var data = {
                name:123,
                value:456
            };
            ajax(
                "http://localhost:8080/orcs/rb/test1.do",
                data,
                "application/x-www-form-urlencoded"
            )
        }

        function test2(){
            var data = [
                {
                    name:123,
                    value:456
                },
                {
                    name:222,
                    value:222
                },
                {
                    name:333,
                    value:444456
                }
            ];

            ajax(
                "http://localhost:8080/orcs/rb/test2.do",
                data,
                "application/x-www-form-urlencoded"
            );
        }

        function test3(){
            var data = [
                {
                    name:123,
                    value:456
                },
                {
                    name:222,
                    value:222
                },
                {
                    name:333,
                    value:444456
                }
            ];

            ajax(
                "http://localhost:8080/orcs/rb/test3.do",
                JSON.stringify(data),
                "application/json"
            );
        }

        function test4(){
            var data = {
                a:[{
                    name:123,
                    value:456
                },
                {
                    name:222,
                    value:222
                },
                {
                    name:333,
                    value:444456
                }],
                count:222
            }

            ajax(
                "http://localhost:8080/orcs/rb/test4.do",
                data,
                "application/x-www-form-urlencoded"
            );
        }

        function test5(){
            var data = {
                a:[{
                    name:123,
                    value:456
                },
                {
                    name:222,
                    value:222
                },
                {
                    name:333,
                    value:444456
                }],
                count:222
            };

            ajax(
                "http://localhost:8080/orcs/rb/test5.do",
                JSON.stringify(data),
                "application/json"
            );
        }
    </script>
</head>
<body>
    <button onclick="test1()">btn1</button>
    <button onclick="test2()">btn2</button>
    <button onclick="test3()">btn3</button>
    <button onclick="test4()">btn4</button>
    <button onclick="test5()">btn5</button>
</body>
</html>

发现@RequestBody这个注解,使用时对ajax有些要求:

  • 数据必需要用JSON.stringify(data)处理
  • contentType类型必需为application/json

而不加这个,注解组装简单对象时,则:

  • 数据直接用json,不必处理
  • contentType类型默认为application/x-www-form-urlencoded即可

转载自《Spring MVC 解决跨域问题&以及对@RequestBody的理解》

猜你喜欢

转载自blog.csdn.net/Code_shadow/article/details/81518666