关于SpringBoot中的参数传递 常用注解 这篇就够了

目录

一、常用注解区别

二、@RequestParam示例

三、@RequestBody示例

四、@Param示例

五、@PathVariable示例


一、常用注解区别

@RequestParam@RequestBody@Param@PathVariable这四个注解在Spring框架中各自具有不同的用途和区别。

  1. @RequestParam:
    • 主要用于接收URL中的查询参数或表单数据中的字段。
    • 通常用于GET请求,但也可以用于POST请求。
    • 在方法参数上添加该注解,可以指定参数名称和是否必需。
    • 示例:@RequestParam("name") String name
  2. @RequestBody:
    • 主要用于处理HTTP请求体中的数据,通常用于POST、PUT等请求方法。
    • 该注解通常与@PostMapping@PutMapping等注解一起使用。
    • 请求体中的数据通常是以JSON、XML等格式发送的,@RequestBody可以将请求体中的数据自动绑定到指定的Java对象上。
    • 示例:@RequestBody User user,其中User是一个自定义的Java类。
  3. @Param:
    • 主要用于命名URI模板变量,使得在控制器方法中可以引用这些变量。
    • 该注解通常与@RequestMapping@GetMapping等注解一起使用。
    • 通过@Param注解可以为URI模板变量提供名称,然后在方法参数中使用该名称来接收变量的值。
    • 示例:@GetMapping("/users/{userId}")public String showUser(@Param("userId") Long id)
  4. @PathVariable:
    • 主要用于接收URI模板变量的值。
    • 该注解通常与@RequestMapping@GetMapping等注解一起使用,用于提取URI中的变量部分。
    • 示例:对于URI /users/{userId},可以使用@PathVariable Long userId来提取{userId}的值。

总结:

  • @RequestParam@PathVariable都是用于从请求中提取参数的,但@RequestParam用于提取查询参数,而@PathVariable用于提取URI模板变量。
  • @RequestBody用于处理请求体中的数据,通常与POST、PUT等请求方法一起使用。
  • @Param主要用于命名URI模板变量,使得在方法参数中可以引用这些变量。

二、@RequestParam示例

html:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Simple Form Example</title>  
</head>  
<body>  
    <h2>Please Fill Out the Form</h2>  
    <form action="/submitForm" method="post">  
        <label for="name">Name:</label>  
        <input type="text" id="name" name="name" required><br><br>  
  
        <label for="age">Age:</label>  
        <input type="number" id="age" name="age" required><br><br>  
  
        <input type="submit" value="Submit">  
    </form>  
</body>  
</html>

controller:

package com.example.demo.controller;  
  
import org.springframework.web.bind.annotation.PostMapping;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.bind.annotation.RestController;  
  
@RestController  
public class FormController {  
  
    @PostMapping("/submitForm")  
    public String handleFormSubmission(@RequestParam String name, @RequestParam int age) {  
        // 处理表单数据  
        // 这里只是简单地将接收到的数据返回给客户端  
        return "Name: " + name + ", Age: " + age;  
    }  
}

三、@RequestBody示例

html:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>Submit Form with Axios</title>  
    <!-- 引入axios -->  
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>  
</head>  
<body>  
  
<!-- 表单 -->  
<form id="submit-form">  
    <label for="name">Name:</label>  
    <input type="text" id="name" name="name">  
      
    <label for="age">Age:</label>  
    <input type="number" id="age" name="age">  
      
    <button type="submit">Submit</button>  
</form>  
  
<!-- JavaScript代码 -->  
<script>  
    // 获取表单元素  
    const form = document.getElementById('submit-form');  
  
    // 为表单添加提交事件监听器  
    form.addEventListener('submit', function(event) {  
        // 阻止表单的默认提交行为  
        event.preventDefault();  
  
        // 获取表单数据  
        const name = document.getElementById('name').value;  
        const age = document.getElementById('age').value;  
  
        // 创建要发送的数据对象  
        const data = {  
            name: name,  
            age: age  
        };  
  
        // 使用axios发送POST请求  
        axios.post('/api/submit', data)  
            .then(response => {  
                // 请求成功处理  
                console.log(response.data); // 打印后端返回的响应数据  
                // 可以在这里更新页面或显示消息给用户  
            })  
            .catch(error => {  
                // 请求失败处理  
                console.error('Error:', error);  
                // 可以在这里显示错误消息给用户  
            });  
    });  
</script>  
  
</body>  
</html>

controller:

import org.springframework.web.bind.annotation.PostMapping;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RestController;  
  
@RestController  
public class MyController {  
  
    @PostMapping("/api/submit")  
    public String handleSubmit(@RequestBody MyData data) {  
        // 处理data对象  
        String name = data.getName();  
        int age = data.getAge();  
          
        // 返回响应  
        return "Data received: " + name + ", " + age;  
    }  
  
 
}

四、@Param示例

@RestController  
public class UserController {  
  
    @GetMapping("/users/{userId}")  
    public String getUser(@Param("userId") Long id) {  
        // 你可以直接使用id参数来查询用户信息  
        return "User with ID: " + id + " was retrieved";  
    }  
}

五、@PathVariable示例

@RestController  
public class UserController {  
  
    @GetMapping("/users/{userId}")  
    public String getUser(@PathVariable Long userId) {  
        // 你可以直接使用userId参数来查询用户信息  
        return "User with ID: " + userId + " was retrieved";  
    }  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

探索星辰大海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值