SpringMVC处理json请求和响应

1.响应json格式的数据

public class JsonController {

    @GetMapping("/login/{username}/{password}")
    public void login(@PathVariable String username, @PathVariable String password, HttpServletResponse res) throws IOException {
        System.out.println(username+"::"+password);
        //响应json格式的字符串
        res.setContentType("application/json;charset=utf-8");
        JsonResult result = JsonResult.builder().code(200).count(100L).data(null).msg("ok").build();
        res.getWriter().write(result.toJSONString());
    }

    @GetMapping("/login2/{username}/{password}")
    @ResponseBody
    public Object login2(@PathVariable String username, @PathVariable String password, HttpServletResponse res) throws IOException {
        System.out.println(username+"::"+password);
        return JsonResult.builder().code(200).count(100L).data(null).msg("ok").build();
    }

    @RequestMapping("/login3")
    @ResponseBody
    public Object login3(User user) {
        System.out.println(user);
        return user;
    }

2.请求数据类型为JSON

 /**
     * 接收json格式的参数
     * @param user
     * @return
     */
    @RequestMapping("/login4")
    @ResponseBody
    public Object login4(@RequestBody User user) {
        System.out.println(user);
        return user;
    }
}


前台ajax请求
<script type="text/javascript">
    $(function () {
        $("#jsbutton").click(function () {
            $.ajax({
                    url:'/login3',
                    type:'post',
                    data:{
                        username:"lisi",
                        age:20,
                        height:170,
                        birth:new Date()
                    },
                    dataType:'json',
                    success:function (result) {
                        console.log(result);
                    },
                    error:function () {
                         console.log("请求失败!")
                     }
            })
        })


        $("#jsbutton2").click(function () {
            var user = {
                username:"lisi",
                age:20,
                height:170,
                birth:'1999-9-9'
            }
            $.ajax({
                url:'/login4',
                type:'post',
                data:JSON.stringify(user),
                contentType:'application/json;charset=utf-8',
                dataType:'json',
                success:function (result) {
                    console.log(result);
                },
                error:function () {
                    console.log("请求失败!")
                }
            })
        })

    })

</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值