【转】 SpringMVC中controller接收Json数据

转自:https://blog.csdn.net/a545415/article/details/77964823

SpringMVC中controller接收Json数据

1.jsp页面发送ajax的post请求:

function postJson(){
    var json = {"username" : "imp", "password" : "123456"};
    $.ajax({
        type : "post",
        url : "<%=basePath %>ajaxRequest",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        data: JSON.stringify(json),
        success : function(data){
            alert("username:"+data.username+"   id:"+data.id);
        },
        error : function(){
            alert("请求失败");
        }
    })
}

注意:

1.在发送数据时,data键的值一定要写成JSON.stringify(json),将数据转换成json格式,否则会抛出异常

2.basePath是项目根目录:

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

2.controller接收请求:

    @ResponseBody
    @RequestMapping(value="/ajaxRequest",method=RequestMethod.POST)
    public User ajaxRequest(@RequestBody User user){
        System.out.println(user);
        return user;
    }

注意:

1.@ResponseBody修饰的方法返回的数据,springmvc将其自动转换成json格式,然后返回给前端

2.@RequestBody修饰目标方法的入参,可以将ajax发送的json对象赋值给入参。当然这里的入参user是我们自定义的实体类型。

3.最后将user返回,springmvc自动将其转换成json返回给前端

猜你喜欢

转载自blog.csdn.net/beidaol/article/details/86233680
今日推荐