1.form请求的后台代码
1.定义实体 Student
package com.bsx.test.entity;import com.bsx.test.constant.Gender;
import com.bsx.test.constant.Nature;import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;@Table(name="t_student")
public class Student implements Serializable {@Idprivate Integer id;private String name;private Integer cId;@Column(name="gender")private Gender gender;@Column(name="nature")private Nature nature;/*** t_student*/private static final long serialVersionUID = 1L;// get set 取消
}
2.后端代码
package com.bsx.test.controller;import com.bsx.test.entity.Student;
import com.bsx.test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/student/")
public class StudentController {@Autowiredprivate StudentService studentService;// 处理json请求@PostMapping("update/json")public Student updateById(@RequestBody Student student) {return studentService.updateByPrimaryKey(student);}// 处理 form请求@PostMapping("update/form")public Student updateById1(Student student) {return studentService.updateByPrimaryKey(student);}
}
3.ajax请求代码
3.1.ajax json请求
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title></title>
</head>
<body>
<script src="js/jquery.js"></script>
<div id="id" class="id">ajax json test</div>
<script>var data = {"id":1,"name": "dada","cId": 4,"gender": "Female","nature":"Optimistic"}$.ajax({url:'http://localhost:8080/student/update/json',method:'post',data: JSON.stringify(data),contentType: "application/json",dataType:'JSON',success:function(result){if(result != null) {alert("修改成功!");}},error:function (data) {}});
</script></body>
</html>
3.2.ajax form 请求
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title></title>
</head>
<body>
<script src="js/jquery.js"></script>
<div id="id" class="id">ajax form test</div>
<script>var data = {"id":1,"name": "xixi","cId": 4,"gender": "Female","nature":"Optimistic"};$.ajax({url:'http://localhost:8080/student/update/form',method:'post',data: data,dataType:'JSON',success:function(result){if(result != null) {alert("修改成功!");}},error:function (data) {}});
</script>
</body>
</html>
4.使用请求发送工具截图:Restlet Client
5.使用 curl 的差别
5.1.curl-json
curl -i -X POST \-H "Content-Type:application/json" \-d \
'{"id":1,"name": "xixi","cId": 4,"gender": "Female","nature":"Optimistic"
}' \'http://localhost:8080/student/update/json'
5.2.curl-form
curl -i -X POST \-H "Content-Type:application/x-www-form-urlencoded" \-d "id=1" \-d "name=xixi" \-d "cId=4" \-d "gender=Female" \-d "nature=Optimistic" \'http://localhost:8080/student/update/form'
总结:
1.ajax提交json数据的时候,需要使用JSON.stringify对数据进行格式化,并且设定contentType: “application/json”
2.使用json提交数据的时候,后台接收数据需要使用 @RequestBody注解来接收,而使用 form 提交的时候不需要任何注解。