springmvc(六)---json数据交互

一、简单应用

1、controller层接收json数据并返回json数据

package top.einino.controller;

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 top.einino.pojo.User;

@Controller
public class UserController {

//@RequestBody将json数据转换成user
//@ResponseBody将user对象转换成json数据
    @RequestMapping("/requestJson.action")
    public @ResponseBody User requestJson(@RequestBody User user){
        return user;
    }

}

2、jsp调用

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function requestJson(){
        $.ajax({
            //请求方式
            type:'post',
            //请求地址
            url:'${pageContext.request.contextPath}/requestJson.action',
            //请求数据类型
            contentType:'application/json;charset=utf-8',
            //请求数据
            data:'{"id":1,"username":"李四"}',
            //回调函数
            success:function(data){
                alert(data.id);
                alert(data.username);
            }
        });
}
</script>
</head>
<body>
<input type="button" οnclick="requestJson()" value="进行json交互"/>
</body>
</html>

3、springmvc中主要配置

<!-- 注解驱动 ,同时包含json数据的转换-->
<mvc:annotation-driven></mvc:annotation-driven>

二、小结

本博文介绍了springmvc的json数据交互,主要利用两个注解@RequestBody和@ResponseBody进行数据的转换。

如果有疑问或者对本博文有何看法或建议或有问题的,欢迎评论,恳请指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值