springboot controller 参数绑定

SpringBoot前后端参数绑定实战
本文介绍如何在SpringBoot项目中实现前后端参数的自动绑定,通过示例展示了User和Privileges对象如何接收并处理来自前端的POST请求数据,包括JSON格式的数据处理和list类型参数的接收。

springboot可以实现前后端参数绑定

普通POST请求

User.java

package cn.ac.iie.bean;

import java.util.List;

public class Privileges {

    private String userName;
    private String authorityType;
    private List<String> authorityApps;

    public Privileges(String userName, String authorityType, List<String> authorityApps) {
        this.userName = userName;
        this.authorityType = authorityType;
        this.authorityApps = authorityApps;
    }

    public Privileges() {
    }

    @Override
    public String toString() {
        return "Privileges{" +
                "userName='" + userName + '\'' +
                ", authorityType='" + authorityType + '\'' +
                ", authorityApps=" + authorityApps +
                '}';
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAuthorityType() {
        return authorityType;
    }

    public void setAuthorityType(String authorityType) {
        this.authorityType = authorityType;
    }

    public List<String> getAuthorityApps() {
        return authorityApps;
    }

    public void setAuthorityApps(List<String> authorityApps) {
        this.authorityApps = authorityApps;
    }
}

新建UserController.java

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/user/add")
    public Object addUser(User user) {
        System.out.println(user);
        return "CREATED";
    }

}

可以直接使用PostMan来模拟发送请求,

d5c2b487a21a8738239a770583d722c2c63.jpg

POST请求,发送JSON数据格式

新建PrivilegesController.java

@RestController
public class PrivilegesController {

    @Autowired
    private PrivilegesService privilegesService;
    @PostMapping("/privileges/add")
    public Object privilegesAdd(@RequestBody Privileges2 privileges2) {
        System.out.println(privileges2);
        return "success";
    }

}

Privileges.java

package cn.ac.iie.bean;

import java.util.List;

public class Privileges {

    private String userName;
    private String authorityType;
    private List<String> authorityApps;

    @Override
    public String toString() {
        return "Privileges{" +
                "userName='" + userName + '\'' +
                ", authorityType='" + authorityType + '\'' +
                ", authorityApps=" + authorityApps +
                '}';
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAuthorityType() {
        return authorityType;
    }

    public void setAuthorityType(String authorityType) {
        this.authorityType = authorityType;
    }

    public List<String> getAuthorityApps() {
        return authorityApps;
    }

    public void setAuthorityApps(List<String> authorityApps) {
        this.authorityApps = authorityApps;
    }
}

bean中包含list,因此需要前端传递数组,后台可以通过spring的@RequestBody直接获取出对应的bean。

postman需要准备的: 

  1. 选post请求 
  2. Headers中添加 key: Content-Type value:application/json 
  3. Body中选raw, JSON(application/json) 
  4. 文本框中写入json参数
{
	"userName": "vincent",
	"authorityType": "mac",
	"authorityApps": ["1","2"]
}

8a3e3e3aec38ac615179bdbcf73127e740f.jpg

这样后台就可以收到对象了

### 使用 `@PathVariable` 和 `@RequestParam` 注解传递参数的方式 在 Spring Boot 的 `@Controller` 中,使用 `@GetMapping` 注解可以定义处理 HTTP GET 请求的方法。为了传递参数,通常可以使用 `@RequestParam` 和 `@PathVariable` 注解。以下是它们的使用方式和区别。 #### 1. 使用 `@RequestParam` 传递参数 `@RequestParam` 用于从请求的查询参数中提取值。GET 请求的参数通常以键值对的形式附加在 URL 的末尾(例如 `/user?id=123`)。可以通过 `@RequestParam` 注解将这些参数绑定方法参数上。 示例代码如下: ```java @GetMapping("/user") public String getUser(@RequestParam("id") Long id) { return "User ID: " + id; } ``` 在上述代码中,`@RequestParam("id")` 表示从请求中提取名为 `id` 的参数,并将其值绑定到 `Long` 类型的变量 `id` 上。如果请求的 URL 是 `/user?id=123`,则 `id` 的值为 `123` [^1]。 此外,`@RequestParam` 还可以省略参数名称,直接通过变量名匹配。例如: ```java @GetMapping("/user") public String user(@RequestParam String username, @RequestParam int age) { return "User: " + username + ", Age: " + age; } ``` 如果请求的 URL 是 `/user?username=John&age=30`,则 `username` 的值为 `"John"`,`age` 的值为 `30` [^3]。 #### 2. 使用 `@PathVariable` 传递参数 `@PathVariable` 用于从 URL 路径中提取值。它通常用于 RESTful 风格的 API 设计中。URL 路径中的变量部分通过 `{}` 定义,然后通过 `@PathVariable` 注解绑定方法参数上。 示例代码如下: ```java @GetMapping("/user/{id}") public String getUserById(@PathVariable("id") Long id) { return "User ID: " + id; } ``` 在上述代码中,`{id}` 表示 URL 路径中的一个变量部分。如果请求的 URL 是 `/user/123`,则 `id` 的值为 `123` [^2]。 #### 3. `@RequestParam` 和 `@PathVariable` 的区别 - **作用位置**: - `@RequestParam` 用于从查询参数中提取值。 - `@PathVariable` 用于从 URL 路径中提取值。 - **适用场景**: - `@RequestParam` 适用于需要传递多个参数的场景。 - `@PathVariable` 适用于需要将参数直接嵌入 URL 路径的场景,通常用于资源标识。 - **可读性**: - `@PathVariable` 提供了更简洁和直观的 URL 结构,适合 RESTful 风格的设计。 - `@RequestParam` 的 URL 结构较为复杂,但支持传递多个参数。 #### 4. 结合使用 `@RequestParam` 和 `@PathVariable` 在实际开发中,可以根据需要同时使用 `@RequestParam` 和 `@PathVariable`。例如: ```java @GetMapping("/user/{id}/details") public String getUserDetails(@PathVariable("id") Long id, @RequestParam("type") String type) { return "User ID: " + id + ", Type: " + type; } ``` 如果请求的 URL 是 `/user/123/details?type=admin`,则 `id` 的值为 `123`,`type` 的值为 `"admin"`。 ### 示例总结 通过 `@RequestParam` 和 `@PathVariable`,可以灵活地从请求中提取参数绑定方法参数上。两者的主要区别在于参数的来源:`@RequestParam` 来自查询参数,而 `@PathVariable` 来自 URL 路径。根据实际需求选择合适的注解可以提高代码的可读性和可维护性 [^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值