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

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

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

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

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


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

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

  1. package maven.example.controller;
  2.  
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestParam;
  5. import org.springframework.web.bind.annotation.RestController;
  6.  
  7. @RestController
  8. @RequestMapping("/index")
  9. public class IndexController {
  10.  
  11. @RequestMapping("/home")
  12. public String home() {
  13. return "Hello World!";
  14. }
  15.  
  16. }

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

前端:

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

后台:

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

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


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

 前端:

  1. let temp = {};
  2. temp.lastName = 'yitian';
  3. temp.firstName = 'zhu';
  4.  
  5. fetch('http://localhost:8080/index/userName', {
  6.   method:'post',
  7.   headers: {
  8.     'Content-Type': 'application/json'
  9.   },
  10.   body:JSON.stringify(temp),
  11. }).then(response => response.text()).then(data => {
  12.   alert(data)
  13. }).catch(function(e){
  14.   alert("error:" + e);
  15. })

后台:

IndexController.java

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

User.java

  1. package maven.example.entity;
  2.  
  3. public class User {
  4.  
  5. private String lastName;
  6. private String firstName;
  7.  
  8. public String getLastName(){
  9. return lastName;
  10. }
  11.  
  12. public void setLastName(String lastName){
  13. this.lastName = lastName;
  14. }
  15.  
  16. public String getFirstName(){
  17. return firstName;
  18. }
  19.  
  20. public void setFirstName(String firstName){
  21. this.firstName = firstName;
  22. }
  23. }

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

前端:

  1. let temp = {};
  2. temp.lastName = 'yitian';
  3. temp.firstName = 'zhu';
  4. fetch('http://localhost:8080/index/mapName', {
  5.   method:'post',
  6.   headers: {
  7.     'Content-Type': 'application/json'
  8.   },
  9.   body:JSON.stringify(temp),
  10. }).then(response => response.text()).then(data => {
  11.   alert(data)
  12. }).catch(function(e){
  13.   alert("error:" + e);
  14. })

后台:

  1. @RequestMapping("mapName")
  2. public String getMapName(@RequestBody Map<String, String> map) {
      return map.get("firstName") + map.get("lastName");
  3. }

4. 上传单个文件或图片

前端:

  1. <form>
  2.   <input type="file" id="picture" />
  3.   <br/>
  4.   <button type="button" onClick={this.handleFile}>上传图片</button>
  5. </form>
  1. handleFile(){
  2.   let picture = document.getElementById("picture").files;
  3.   let formData = new FormData();
  4.   formData.append('file', picture[0]);//这里的file要与后台@RequestParam的参数值相对应
  5.  
  6.   fetch('http://localhost:8080/index/getPicture', {
  7.     method:'post',
  8.     body:formData,
  9.   }).then(response => response.text()).then(data => {
  10.     alert(data)
  11.   }).catch(function(e){
  12.     alert("error:" + e);
  13.   })
  14. }

后台:

  1. @RequestMapping("getPicture")
  2. public String handleFormUpload(@RequestParam("file") MultipartFile file) {
  3. try{
  4. if (!file.isEmpty()) {
  5. byte[] bytes = file.getBytes();
  6. File picture = new File("temp.png");//这里指明上传文件保存的地址
  7. FileOutputStream fos = new FileOutputStream(picture);
  8. BufferedOutputStream bos = new BufferedOutputStream(fos);
  9. bos.write(bytes);
  10. bos.close();
  11. fos.close();
  12. return "success";
  13. }
  14. }catch (IOException e){
  15. System.out.println(e);
  16. }
  17. return "failed";
  18. }

5.上传多个文件或图片

前端:

  1. <form>
  2.   <input type="file" id="picture" multiple="multiple"/>
  3.   <br/>
  4.   <button type="button" onClick={this.handleFile}>上传图片</button>
  5. </form>
  1. handleFile(){
  2.   let picture = document.getElementById("picture").files;
  3.   let formData = new FormData();
  4.  
  5.   for (let i = 0; i < picture.length; ++i){
  6.     formData.append('file', picture[i]);
  7.   }
  8.  
  9.   fetch('http://localhost:8080/index/getPictures', {
  10.     method:'post',
  11.     body:formData,
  12.   }).then(response => response.text()).then(data => {
  13.     alert(data)
  14.   }).catch(function(e){
  15.     alert("error:" + e);
  16.   })
  17. }

后台:

  1. @RequestMapping("getPictures")
  2. public String handleFormsUpload(HttpServletRequest request) {
  3. try{
  4. List<MultipartFile>files = ((MultipartHttpServletRequest) request).getFiles("file");
  5.  
  6. MultipartFile file = null;
  7.  
  8. for(int i = 0; i < files.size(); ++i){
  9. file = files.get(i);
  10. if (!file.isEmpty()) {
  11. byte[] bytes = file.getBytes();
  12. File picture = new File("temp" + String.valueOf(i) + ".png");//这里指明上传文件保存的地址
  13. FileOutputStream fos = new FileOutputStream(picture);
  14. BufferedOutputStream bos = new BufferedOutputStream(fos);
  15. bos.write(bytes);
  16. bos.close();
  17. fos.close();
  18. }
  19. }
  20.  
  21. return "success";
  22.  
  23. }catch (IOException e){
  24. System.out.println(e);
  25. }
  26. return "failed";
  27. }

Springboot第三篇:与前端fetch通信(关于前端传输json数据上传文件等等前后端的处理)的更多相关文章

  1. 重新想象 Windows 8.1 Store Apps (89) - 通信的新特性: 下载数据, 上传数据, 上传文件

    [源码下载] 重新想象 Windows 8.1 Store Apps (89) - 通信的新特性: 下载数据, 上传数据, 上传文件 作者:webabcd 介绍重新想象 Windows 8.1 Sto ...

  2. 《手把手教你》系列技巧篇(五十四)-java+ selenium自动化测试-上传文件-中篇(详细教程)

    1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...

  3. Springboot第二篇:与前端fetch通信(附springboot解决跨域方法)

    说到与前端通信,明白人都知道这章肯定会写两部分的东西啦. 关于后台 ①首先回顾前文,上一章环境搭建如图: ②我们在maven.example.controller下添加一个文件,并附上如图代码: ③: ...

  4. SpringBoot非官方教程 | 第十七篇:上传文件

    转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot14-upload/ 本文出自方志朋的博客 这篇文 ...

  5. 第九篇:web之前端之web上传文件的方式

    前端之web上传文件的方式   前端之web上传文件的方式 本节内容 web上传文件方式介绍 form上传文件 原生js实现ajax上传文件 jquery实现ajax上传文件 form+iframe构 ...

  6. fetch上传文件报错的问题(multipart: NextPart: EOF)

    技术栈 后台: gin(golang) 前端: react+antd+dva 问题 前端这边使用fetch发送http请求的时候,后端解析formData报错: multipart: NextPart ...

  7. 基于spring-boot的web应用,ckeditor上传文件图片文件

    说来惭愧,这个应用调试,折腾了我一整天,google了很多帖子,才算整明白,今天在这里做个记录和分享吧,也作为自己后续的参考! 第一步,ckeditor(本博文论及的ckeditor版本4.5.6)的 ...

  8. 三种方式上传文件-Java

    前言:负责,因为该项目他(jetty嵌入式开始SpringMvc)实现文件上传的必要性,并拥有java文件上传这一块还没有被曝光.并 Http 更多晦涩协议.因此,这种渐进的方式来学习和实践上载文件的 ...

  9. java前后分离使用fetch上传文件失败500

    这次不是写什么技术要点,仅仅是记录一下 最近遇到的一个问题 背景 使用fetch向java后台上传文件时,前端调试报错500,后端的报错为multipart 无法解析,翻译过来大概是这个意思. 由于本 ...

随机推荐

  1. Python 中 "is" 与 "==" 操作有什么区别?

    转自:https://foofish.net/what-is-difference-between-is-and-euqals.html 在 Python 中,比较两个对象(变量)是否相等,可以用 & ...

  2. [C++] * Basic and Class

    C++ 目  录 1 开始学习C++ 4 1.1 C++的头文件 4 1.2 命名空间 4 1.3 更严格的类型转化 4 1.4 new和delete 4 1.5 内联函数 4 1.6 引用 5 1. ...

  3. N-Gram的数据结构

    ARPA的n-gram语法如下: [html] view plaincopyprint? \data\ ngram 1=64000 ngram 2=522530 ngram 3=173445 \1-g ...

  4. C#中把任意类型的泛型集合转换成SQLXML数据格式的小例子

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  5. 【#】Spring3 MVC 注解(一)---注解基本配置及@controller和 @RequestMapping 常用解释

    Spring3 MVC 注解(一)---注解基本配置及@controller和 @RequestMapping 常用解释 博客分类:  spring MVCSpringWebXMLBean  一:配置 ...

  6. git post-receive 待验证的代码

    使用 git post-receive 钩子部署服务端代码 本站文章除注明转载外,均为本站原创或者翻译. 本站文章欢迎各种形式的转载,但请18岁以上的转载者注明文章出处,尊重我的劳动,也尊重你的智商: ...

  7. mysql问题,出现 Cant connect to mysql server on 'localhost'

    莫名其妙的一个问题,这个问题出现在今天,然后查找下,发现需要重启服务器,但是重启也一样,于是关机重启,还是这个现象 ,然后看到 错误提示, 提示my.ini的第21行,产生错误,于是按照路径找到配置文 ...

  8. java中Integer常量池

    我们先看一个关于Integer的例子 public static void main(String[] args) { // TeODO Auto-generated method stu Integ ...

  9. webapi 跨域访问设置基于jsonp跨域

    JSONP实现跨域 Web API并没有提供JSONP  Formatter,但是这并不能影响我们前进的脚步,我们可以自定义Formatter来实现JSONP功能.既然是利用JSONP跨域,那么就得简 ...

  10. NetBeans找不到C/C++编译器

    如果您已经安装 NetBeans IDE 6.9,但其中不包括 C/C++ 插件 如果在选择“文件”>“新建项目”时,NetBeans IDE 未显示 "C/C++" 项目类 ...