从前台用js向 springmvc中传递 json。在controller中转换为java对象需要用 @RequestBody 注解。但是传递时有几个问题可能会导致无法访问。
1.ajax中必须用json对象:JSON.stringify({"name":name,"age":age,"sex":sex})
2.ajax中必须设置 contentType:"application/json",
3.否则会报 415或者400错误。
直接上代码:
前台:
<html>
<head>
<title></title>
</head>
<body>
<div>
name:<input type="text" id="name"> <br>
sex:<input type="text" id="sex"><br>
age:<input type="text" id="age"><br>
<button type="button" id="btn">提交</button>
</div>
<script src="js/jquery-3.3.1.js"></script>
<script>
$("#btn").click(function(){
var name = $("#name").val();
var sex = $("#sex").val();
var age = $("#age").val();
$.ajax({
type: "POST",
url: "test03",
contentType:"application/json",
data: JSON.stringify({"name":name,"age":age,"sex":sex}),
success: function(data){
if(data.msg==1){
alert("success");
}else{
alert("error");
}
}
});
})
</script>
</body>
</html>
controller
@ResponseBody
@RequestMapping("/test03")
public Map<String,Object> test03(@RequestBody User user){
Map<String,Object> map = new HashMap<>();
if(user!=null){
map.put("msg","1");
}else{
map.put("msg","0");
}
return map;
}
实体类
public class User {
private String name;
private int age;
private String sex;
public User() {
}
public User(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}