json數(shù)據(jù)交互
客戶端發(fā)送請求一共2種方式j(luò)son回來
1.key value 原生js請求
2.json方式
html---------->Controller
以下有2種方式
1.請求json過渡到過濾器
2.過濾器如何快速返json
這個是通過url地址來傳值
http://localhost:8080/TestSpringMvc/ajax/test1?empno=1&empname=2&sal=3
@Controller
@RequestMapping("/ajax")
public class AjaxController {
/*
* content-type:application/x-www-form-urlencoded=> 1.test(Integer empno, String empname, Double sal)
* content-type:application/json => @RequestBody Employee e
* @RequestBody:解析json字符串苟鸯,把請求數(shù)據(jù)拿出來,放在對象里
*
*/
//http://localhost:8080/TestSpringMvc/ajax/test1?empno=1&empname=2&sal=3
//test1 通過一個一個傳遞屬性來獲得
@RequestMapping("/test1")
public void test1(Integer empno,String empname,Double sal ,HttpServletResponse resp) {
System.out.println(empno);
System.out.println(empname);
System.out.println(sal);
try {
resp.getWriter().append("{\"result\":true}");
} catch (IOException e) {
e.printStackTrace();
}
}
}
顯示地址不一樣
第二種方式這個是通過阿賈克斯來傳,請求數(shù)據(jù)組裝成(節(jié)深)字符串形式向Springmvc發(fā)送放到@RequestBody Employee e 字符串形式和解析出來放到這里
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
function test()
{
axios.post('/TestSpringMvc/ajax/test2',
{
empno:1,
empname:"feiyy",
sal:10000
}).then(function(resp){
console.log(resp);
})
}
</script>
</head>
<body>
<button type="button" onclick="test()">測試</button>
</body>
</html>
@Controller
@RequestMapping("/ajax")
public class AjaxController {
/*
* content-type:application/x-www-form-urlencoded=> 1.test(Integer empno, String empname, Double sal)
* content-type:application/json => @RequestBody Employee e
* @RequestBody:解析json字符串蚕钦,把請求數(shù)據(jù)拿出來懊烤,放在對象里
*
*/
//http://localhost:8080/TestSpringMvc/ajax/test1?empno=1&empname=2&sal=3
//test1 通過一個一個傳遞屬性來獲得
@RequestMapping("/test1")
public void test1(Integer empno,String empname,Double sal ,HttpServletResponse resp) {
System.out.println(empno);
System.out.println(empname);
System.out.println(sal);
try {
resp.getWriter().append("{\"result\":true}");
} catch (IOException e) {
e.printStackTrace();
}
}
//test2 通過前端js框架組裝字符串 到這里進(jìn)行字符串解析 成為類獲得值
@RequestMapping("/test2")
public void test(@RequestBody Employee e, HttpServletResponse resp)
{
System.out.println(e.getEmpno());
System.out.println(e.getEmpname());
System.out.println(e.getSal());
try {
resp.getWriter().append("{\"result\":true}");
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
}
數(shù)據(jù)已經(jīng)傳給Controller 數(shù)據(jù)如何通過controller傳送給頁面扮念!
在SpringMvc有個處理,返回是一個對象或者一個集合在方法返回值上面加個
@RequestBody
@RequestMapping("/test3")
@ResponseBody
public List<Employee> test(@RequestBody Employee e)
{
System.out.println(e.getEmpno());
System.out.println(e.getEmpname());
System.out.println(e.getSal());
List<Employee> list = new ArrayList<>();
Employee e1 = new Employee();
e1.setEmpno(1);
e1.setEmpname("jack");
Employee e2 = new Employee();
e2.setEmpno(2);
e2.setEmpname("james");
list.add(e1);
list.add(e2);
return list;
}
**還是通過 輸入ajax地址返回來還是一個對象
html---->controller springMVC
html向controller走的時候颠区,是組裝成json字符串過去的
html----controller 艾克壽司做的
StringMVC解析json字符串組裝成對象放到控制器里荠割,然后查詢數(shù)據(jù)庫棵帽,列表打印成json字符串梨树,把列表打成json字符串發(fā)送到客戶端來了調(diào)用了一個組件
@RequestBody SpringMvc
@ResponseBody json
如果一個controller下,都是響應(yīng)ajax請求岖寞,@RestController = @Controller + @ResponseBody
如何通過字符串返回客戶端
package com.fcx.bean;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
public class Employee {
private int empno;
private String empname;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date hiredate;
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
}
@RestController
@RequestMapping("/ajax2")
public class AjaxController2 {
/*
* content-type:application/x-www-form-urlencoded=> 1.test(Integer empno, String empname, Double sal)
* content-type:application/json => @RequestBody Employee e
* @RequestBody: 解析json字符串,把請求數(shù)據(jù)拿出來柜蜈,放在對象里仗谆。
*
*/
@RequestMapping("/test1")
public List<Employee> test(@RequestBody Employee e)
{
System.out.println(e.getEmpno());
System.out.println(e.getEmpname());
List<Employee> list = new ArrayList<>();
Employee e1 = new Employee();
e1.setEmpno(1);
e1.setEmpname("jack");
e1.setHiredate(new Date());
Employee e2 = new Employee();
e2.setEmpno(2);
e2.setEmpname("james");
e2.setHiredate(java.sql.Date.valueOf("1987-01-01"));
list.add(e1);
list.add(e2);
return list;
}
}
用阿賈克斯文件上傳
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
function upload()
{
var filesize = document.getElementById("avatar").files[0].size;
if(filesize>5242880)
{
alert("文件超過最大限制5M");
return;
}
//使用FormData,表單上必須是multipart/form-data,二進(jìn)制提交給后臺的。
//1. 創(chuàng)建FormData對象淑履,
var formData = new FormData(document.getElementById("myform"));
//2. 發(fā)送ajax請求
axios.post('/TestSpringMvc/upload2/upload',formData)
.then(function(resp){
console.log(resp);
})
}
</script>
</head>
<body>
<!-- ajax做文件上傳的時候隶垮,需要表單,表單需要設(shè)置enctype="multipart/form-data",method="post" -->
<form id="myform" enctype="multipart/form-data" method="post">
<div>
<input type="text" name="username" />
</div>
<div>
<input type="date" name="birthday" />
</div>
<div>
<input id="avatar" type="file" name="avatar"/>
</div>
<button type="button" onclick="upload()">提交</button>
</form>
</body>
</html>
@Controller
@RequestMapping("/upload2")
public class UploadController2 {
@RequestMapping("/upload")
public void upload(String username, Date birthday, MultipartFile avatar, HttpServletResponse resp)
{
System.out.println("JAJAJAJAJA");
System.out.println(username);
System.out.println(birthday);
System.out.println(avatar.getOriginalFilename());
String newfilename = UUID.randomUUID().toString()+avatar.getOriginalFilename().substring(avatar.getOriginalFilename().lastIndexOf("."));
File dest = new File("d:/images",newfilename);
try {
avatar.transferTo(dest);
} catch (IllegalStateException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
resp.getWriter().append("{\"result\":true}");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
RESTFUl面向資源一種請求
restui面向資源的秘噪,你原來對比一下狸吞,現(xiàn)在請求url
get emp查詢,set emp ,delete emp
蹋偏,url加動詞體現(xiàn)干啥便斥,你不應(yīng)該這樣寫面向資源方式寫,你操作員工威始,你想查詢所有員工 emps 配合請求方式get然后你想往這里面新增一個路徑emps
只是提交方式post枢纠,我想用id查詢員工信息 emp/員工編號101或者員工102更像他還是這一個資源
更新 put 刪除101 delte 在這種架構(gòu)下,面向資源黎棠,在url路徑下不應(yīng)該有資源配合請求方式
@RestController
public class RestFullController {
@GetMapping("/emps")
public List<Employee> getEmps()
{
List<Employee> list = new ArrayList<>();
Employee e = new Employee();
e.setEmpno(1);
e.setEmpname("jack");
e.setHiredate(new Date());
Employee e2 = new Employee();
e2.setEmpno(2);
e2.setEmpname("james");
e2.setHiredate(java.sql.Date.valueOf("1990-1-1"));
list.add(e);
list.add(e2);
return list;
}
@PostMapping("/emps")
public String addEmp(Employee e)
{
System.out.println(e.getEmpno());
System.out.println(e.getEmpname());
System.out.println(e.getHiredate());
//add to database
return "{\"result\":true}";
}
@GetMapping("/emp/{id}")
public Employee getEmployee(@PathVariable int id)
{
System.out.println(id);
return new Employee();
}
@DeleteMapping("/emp/{id}")
public String deleteEmployee(@PathVariable int id)
{
System.out.println(id);
return "{\"result\":true}";
}
@PutMapping("/emp/{id}")
public String updateEmployee(@PathVariable int id, Employee e)
{
System.out.println(id);
System.out.println(e.getEmpno());
System.out.println(e.getEmpname());
System.out.println(e.getHiredate());
//add to database
return "{\"result\":true}";
}
}
加個過濾器
<!--RESTFUl-->
<filter>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>