//实现序列化对象
import java.io.Serializable;
public class User implements Serializable {
private String id;
private Integer age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getAge() {
return age;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", age=" + age +
'}';
}
public void setAge(Integer age) {
this.age = age;
}
}
前端代码
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/5/19 0019
Time: 10:02
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function testjson() {
var id=$("#id").val();
var age=$("#age").val();
$.ajax({
url:"user/testAjax",
type:"post",
contentType:"application/json;charset=UTF-8",
data:JSON.stringify({id:id,age:age}),
dataType:"json",
success:function (data) {
alert("参数传递成功")
if(data!=null)
alert("输入合法的数值"+data.age+" "+data.id);
}
}
)
}
</script>
<title>Title</title>
</head>
<body>
<form>
账号:<input type="text" name="id" id="id">
年龄: <input type="text" name="age" id="age">
<input type="button" value="json交互" onclick="testjson()">
</form>
</body>
</html>
控制层代码
package cn.itcast.controller;
import cn.itcast.domin.User;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
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;
@Controller
@RequestMapping("user")
public class Recontroller {
@RequestMapping(value="testAjax")
@ResponseBody
public User AJAX(@RequestBody User user){
System.out.println("传递参数");
System.out.println(user);
return user;
}
}