后端如何接收前端发出的请求中的参数?

package org.springframework.web.bind.annotation; 中的注解

1.@RequestParam,用于将 HTTP 请求中的参数绑定到控制器方法的参数上。

  • 他可以绑定GET/POST/PUT/DELETE请求的查询参数(查询参数附加在 URL 的末尾)
    如:GET http://localhost:8080/user?status=active
  • 可以绑定POST请求中的表单数据(application/x-www-form-urlencoded 或 multipart/form-data格式的表单数据都可以绑定)
    2.@RequestBody,用于将POST/PUT请求中,请求体的JSON格式的数据绑定到方法参数上。

1.将参数接收到后端的实体类中

1.1如果前端发出的参数在URL中

如果前端发出的参数在URL中,你可以使用 @ModelAttribute 注解。这样可以将请求中的参数自动绑定到实体类上。

前端发出的请求
GET /users?name=Alice&age=30

你的实体类

public class User {
    private String name;
    private int age;

    // Getter 和 Setter
}

你的Controller

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping
    public String getUser(@ModelAttribute User user) {
        // 处理用户
        return "User received: " + user.getName() + ", Age: " + user.getAge();
    }
}

1.2如果前端发出的参数在请求体中

如果前端发出的参数在请求体中,并且请求体中包含与后端实体类属性相对应的数据时,可以使用 @RequestBody 注解来直接将请求体映射到实体类。
前端发出的请求

POST /users
Content-Type: application/json

{
    "name": "Alice",
    "age": 30
}

你的实体类

public class User {
    private String name;
    private int age;

    // Getter 和 Setter
}

你的Controller

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    @PostMapping
    public String createUser(@RequestBody User user) {
        // 处理用户
        return "User created: " + user.getName() + ", Age: " + user.getAge();
    }
}

2.将URL中的单个参数绑定到后端的单个参数中

说明:使用 @RequestParam,你可以将URL中的单个参数直接绑定到后端方法的单个参数中。如果参数名称与请求参数名称不匹配,可以通过 name 属性指定。

前端发出的请求
/users?name=Alice&age=30

你的Controller

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping
    public String getUserInfo(@RequestParam("name") String name, @RequestParam("age") int age) {
        // 处理单个参数
        return "User info: " + name + ", Age: " + age;
    }
}

3.发送并接收表单数据(表单中可以选择文件,把文件发送)

如果想把excel文件导入到后端,可以把文件放入表单中,并把表单提交,后端此时可以通过@RequestParam接收每一个表单项。
@RequestParam 通常用于从 URL 查询参数中获取数据,但在某些情况下(比如表单提交),它也可以从请求体中获取数据。

html中的写法:

<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="text" name="description" />
    <input type="file" name="file" />
    <button type="submit">Upload</button>
</form>

Spring Boot 处理:

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public String handleFileUpload(
            @RequestParam String description,
            @RequestParam MultipartFile file) {
        
        // 处理文本字段
        System.out.println("Description: " + description);
        
        // 处理文件
        if (!file.isEmpty()) {
            try {
                String fileName = file.getOriginalFilename();
                byte[] bytes = file.getBytes();
                // 保存文件到指定路径
                // ...
                return "File uploaded successfully: " + fileName;
            } catch (IOException e) {
                e.printStackTrace();
                return "File upload failed";
            }
        } else {
            return "No file selected";
        }
    }
}

ELement框架中的写法:

<!--点击新增按钮后弹出以下对话框,里面是一个表单-->
    <el-dialog title="导入数据" :visible.sync="showImportDataDialog" :close-on-click-modal="false" width="600px">
      <el-form :inline="true" label-width="148px">
      
        <el-form-item label="版本名称" prop="versionName">
          <el-input v-model="newForm.versionName" style="width:220px" placeholder="请输入版本名称"></el-input>
        </el-form-item>

        <div class="upload1">
          <span style="color: red;">温馨提示:请选择文件1</span>
          <input type='file' @change="getFile($event)"/>
        </div>

        <div class="upload2">
          <span style="color: red;">温馨提示:请选择文件2</span>
          <input type='file' @change="getFile2($event)"/>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="showImportDataDialog = false">取消</el-button>
        <el-button type="primary" @click.native="importData($event)">导入</el-button>
      </div>
    </el-dialog>
    
 // 选择文件1
    getFile(event) {
      console.log('版本规则管理-选择业务模型')
      this.file = event.target.files[0]
      console.log(this.file)
    },
 //选择文件2
    getFile2(event) {
      console.log('版本规则管理-选择记账规则')
      this.file2 = event.target.files[0]
      console.log(this.file2)
    },  
// 新增导入
        importData(event) {
            console.log('版本规则管理-新增导入')
            if (this.file == '' && this.file2 != '') {
                this.$message.error('请选择业务模型!')
            } else if (this.file != '' && this.file2 == '') {
                this.$message.error('请选择记账规则!')
            } else if (this.file == '' && this.file2 == '') {
                this.$message.error('请选择业务模型和记账规则!')
            } else {
                // 取消默认行为
                event.preventDefault()
                // 创建 formData 对象
                let formData = new FormData()
                // 向 formData 对象中添加文件
                formData.append('excelBusTemp', this.file)
                formData.append('excelAccTemp', this.file2)
                formData.append('versionName', this.newForm.versionName)
                console.log('导入文件', formData)
                this.$message({
                    showClose: false,
                    message: '版本正在创建中,请耐心等待......',
                    type: 'success'
                })
                Edition.addEdition(formData).then((res) => {
                    console.log('新增导入', res)
                    this.$message({
                        showClose: true,
                        message: res.message,
                        type: 'success'
                    })
                    this.showImportDataDialog = false
                    this.getEditions()
                })
            }
    },    
 
 // 新增
    addEdition(params) {
        return http.post(URL + '/versions/add', params)
    },
    
 <style lang="less" scoped>
.upload1 {
  margin-bottom: 50px;
  margin-top: 35px;
  margin-left: 80px;
}

.upload2 {
  margin-bottom: 35px;
  margin-left: 80px;
}
</style>

后端接收表单中的参数

 @ResponseBody
    @RequestMapping("/add")
    public ResultModel versionAdd(@RequestParam(value = "excelBusTemp", required = true) MultipartFile busMultiFile,
                                  @RequestParam(value = "excelAccTemp", required = true) MultipartFile accMultiFile,
                                  @RequestParam(value = "versionName", required = true) String versionName) {
        String versionNo ="";

4.表单的multipart/form-data格式和application/x-www-form-urlencoded格式的区别

表单参数有 application/x-www-form-urlencoded 格式和 multipart/form-data 格式。
注意:application/form-data是一个错误的写法。

application/x-www-form-urlencoded,格式是最简单的表单数据编码格式。它适用于包含文本数据的表单,但不支持文件上传。
multipart/form-data,适用于包含文件上传和复杂数据的表单。它可以同时处理文本字段和文件字段。

1. application/x-www-form-urlencoded

特点:

  • 文本数据:仅适用于不包含文件的表单。
  • 编码方式:数据被编码为 key=value 的形式,多个键值对之间用 & 分隔。例如:name=John&age=30
  • 请求头部:请求头部通常包含 Content-Type: application/x-www-form-urlencoded

示例:

HTML 表单:

<form action="/submit" method="post">
    <input type="text" name="name" />
    <input type="number" name="age" />
    <button type="submit">Submit</button>
</form>

提交的请求体:

name=John&age=30

Spring Boot 处理:

@PostMapping("/submit")
public String submitForm(
        @RequestParam String name,
        @RequestParam int age) {
    return "Received: Name=" + name + ", Age=" + age;
}

2. multipart/form-data

特点:

  • 文件上传:支持文件上传,多个文件和文本字段可以混合提交。
  • 编码方式:数据被分割成多个部分,每个部分表示一个表单字段(文本字段或文件字段)。
  • 请求头部:请求头部必须包含 Content-Type: multipart/form-data; boundary=xxx,其中 boundary 是一个分隔符,用于分隔不同的表单字段。

示例:

HTML 表单:

<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="text" name="description" />
    <input type="file" name="file" />
    <button type="submit">Upload</button>
</form>

提交的请求体:

POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="description"

text的内容
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="example.txt"
Content-Type: text/plain

文件中的内容,以二进制发送..................................................
------WebKitFormBoundary7MA4YWxkTrZu0gW--

Spring Boot 处理:

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public String handleFileUpload(
            @RequestParam String description,
            @RequestParam MultipartFile file) {
        
        // 处理文本字段
        System.out.println("Description: " + description);
        
        // 处理文件
        if (!file.isEmpty()) {
            try {
                String fileName = file.getOriginalFilename();
                byte[] bytes = file.getBytes();
                // 保存文件到指定路径
                // ...
                return "File uploaded successfully: " + fileName;
            } catch (IOException e) {
                e.printStackTrace();
                return "File upload failed";
            }
        } else {
            return "No file selected";
        }
    }
}
在Layui前端写好按钮后,后端是通过接收前端发出的按钮请求来进行相应的处理。具体来说,后端需要通过某种方式与前端进行数据输,通常使用的是HTTP协议。 在前端,我们可以使用Layui的按钮组件,并在点击按钮时触发相应的事件,可以是跳转页面、发送请求或其他操作。当点击按钮时,会向后端发送一个HTTP请求后端接收请求后,需要对请求进行处理。具体处理方式根据具体业务需求而定,但一般包括以下几个步骤: 1. 接收请求后端通过监听某个端口,如80端口,接收前端发送的HTTP请求。 2. 解析请求参数后端需要解析请求参数,可以通过获取URL参数,或者通过POST方式将参数放在请求的body,然后使用相应的解析工具将参数解析出来。 3. 处理业务逻辑:根据接收到的请求参数后端进行相应的业务逻辑处理,可以是读取、写入数据库,调用其他接口等。 4. 返回响应结果:后端处理完业务逻辑后,需要将处理结果封装成HTTP响应,包括返回状态码、响应头和响应体等信息,并将响应发送给前端。 总结来说,Layui前端写好按钮只是前端界面的一部分,当我们点击按钮时,会触发向后端发送HTTP请求的操作。而后端需要接收请求、解析参数、处理业务逻辑,并将结果封装成HTTP响应返回给前端。通过这样的前后端交互,实现了按钮的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值