博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Springboot第三篇:与前端fetch通信(关于前端传输json数据上传文件等等前后端的处理)...
阅读量:4537 次
发布时间:2019-06-08

本文共 5232 字,大约阅读时间需要 17 分钟。

关于前端接口传递的方法,推荐按以下使用:

 

若要在服务器上创建资源,推荐使用POST方法

若要检索某个资源,推荐使用GET方法

若要更新资源,推荐使用PUT方法

若要删除某个资源,推荐使用DELETE方法

 


 

 

另外本章主要讲述的是关于前后端通信关于对应性,前端为react的View,会分传递不同值有不同的处理情况。

 

首先关于Springboot内的代码变更都是在IndexController.java内,以下是代码:

package maven.example.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/index")public class IndexController {    @RequestMapping("/home")    public String home() {        return "Hello World!";    }    }
View Code

 


 

1:传递普通类型的数据,如string

 

前端:

fetch('http://localhost:8080/index/name', {  method:'post',  headers: {    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"  },  body:"firstName=zhu&lastName=yitian",}).then(response => response.text()).then(data => {  alert(data)}).catch(function(e){  alert("error:" + e);})

 

后台:

 @RequestMapping("name")     public String getName(@RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName) {
        return firstName + lastName;     }

 

@RequestParam:用于访问 Servlet 请求参数。参数值转换为已声明的方法参数类型。

 


 

2:传递Json类型的数据,接收方为类

 

 前端:

let temp = {};temp.lastName = 'yitian';temp.firstName = 'zhu';fetch('http://localhost:8080/index/userName', {  method:'post',  headers: {    'Content-Type': 'application/json'  },  body:JSON.stringify(temp),}).then(response => response.text()).then(data => {  alert(data)}).catch(function(e){  alert("error:" + e);})

 

后台:

 

IndexController.java

 @RequestMapping("userName")     public String getUserName(@RequestBody User user) {
        return user.getFirstName() + user.getLastName();     }

 

User.java

package maven.example.entity;public class User {    private String lastName;    private String firstName;        public String getLastName(){        return lastName;    }        public void setLastName(String lastName){        this.lastName = lastName;    }        public String getFirstName(){        return firstName;    }        public void setFirstName(String firstName){        this.firstName = firstName;    }}

 

 


 

3:传递Json类型的数据, 接收方为map

 

前端:

let temp = {};temp.lastName = 'yitian';temp.firstName = 'zhu'; fetch('http://localhost:8080/index/mapName', {  method:'post',  headers: {    'Content-Type': 'application/json'  },  body:JSON.stringify(temp),}).then(response => response.text()).then(data => {  alert(data)}).catch(function(e){  alert("error:" + e);})

 

后台:

@RequestMapping("mapName")public String getMapName(@RequestBody Map
map) {
  return map.get("firstName") + map.get("lastName");}

 


 

4. 上传单个文件或图片

 

前端:

  
  
  
handleFile(){  let picture = document.getElementById("picture").files;  let formData = new FormData();  formData.append('file', picture[0]);//这里的file要与后台@RequestParam的参数值相对应  fetch('http://localhost:8080/index/getPicture', {    method:'post',    body:formData,  }).then(response => response.text()).then(data => {    alert(data)  }).catch(function(e){    alert("error:" + e);  })    }

 

后台:

@RequestMapping("getPicture")    public String handleFormUpload(@RequestParam("file") MultipartFile file) {        try{            if (!file.isEmpty()) {                byte[] bytes = file.getBytes();                File picture = new File("temp.png");//这里指明上传文件保存的地址                FileOutputStream fos = new FileOutputStream(picture);                  BufferedOutputStream bos = new BufferedOutputStream(fos);                bos.write(bytes);                bos.close();                fos.close();                return "success";            }        }catch (IOException e){            System.out.println(e);        }        return "failed";    }

 


 

5.上传多个文件或图片

 

前端:

  
  
  
handleFile(){
  let picture = document.getElementById("picture").files;  let formData = new FormData();  for (let i = 0; i < picture.length; ++i){    formData.append('file', picture[i]);  }  fetch('http://localhost:8080/index/getPictures', {    method:'post',    body:formData,  }).then(response => response.text()).then(data => {    alert(data)  }).catch(function(e){    alert("error:" + e);  }) }

 

后台:

@RequestMapping("getPictures")    public String handleFormsUpload(HttpServletRequest request) {        try{            List
files = ((MultipartHttpServletRequest) request).getFiles("file"); MultipartFile file = null; for(int i = 0; i < files.size(); ++i){ file = files.get(i); if (!file.isEmpty()) { byte[] bytes = file.getBytes(); File picture = new File("temp" + String.valueOf(i) + ".png");//这里指明上传文件保存的地址 FileOutputStream fos = new FileOutputStream(picture); BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write(bytes); bos.close(); fos.close(); } } return "success"; }catch (IOException e){ System.out.println(e); } return "failed"; }

 

转载于:https://www.cnblogs.com/tianshu/p/9218309.html

你可能感兴趣的文章
spring不同环境下用不同的配置文件
查看>>
数组_leetcode80
查看>>
SQL Error (1130): Host '192.168.1.100' is not allowed to connect to this MySQL server
查看>>
普通线程类获取service,controller等spring容器类
查看>>
Redis高级实践之————Redis短连接性能优化
查看>>
ThreadLocal使用
查看>>
POJ - 2155 Matrix(二维树状数组)
查看>>
基于Cat的分布式调用追踪
查看>>
建筑物联动
查看>>
汇编语言 手记5
查看>>
牛客网暑期ACM多校训练营(第三场) E-Sort String next数组的应用
查看>>
如何成功的捕捉一只女神
查看>>
有关HTTP的粗读
查看>>
连接mysql数据库,创建用户模型
查看>>
Uncaught TypeError: (intermediate value)(...) is not a function
查看>>
NOIP模拟:能源(二分答案)
查看>>
模拟I2C协议学习点滴之原理框架
查看>>
数组中重复的数字
查看>>
scipy插值interpolation
查看>>
C# BackgroundWorker
查看>>