Spring学习笔记_38——@RequestParam

@RequestParam注解

1. 介绍

RequestParam 是一个在 Java Web 开发中常用的注解,它属于 Spring 框架的一部分,用于处理 HTTP 请求中的参数。

RequestParams 注解用于将 HTTP 请求参数绑定到控制器处理方法的参数上。当一个控制器方法需要接收来自 HTTP 请求的参数时,可以使用此注解来指定参数的名称和其它属性

2. 场景

@RequestParam注解主要用于获取请求的参数值,斌关切为控制器类中的方法形参的参数赋值。

如果请求参数的名称与控制器中方法的形参的参数名称一致,@RequestParam注解可以省略。

如果使用@RequestParam注解没有获取到参数值时,可以使用@RequestParam注解提供默认的参数值。

  • 简单查询参数:当需要从GET去请求获取单个参数或多个参数时。
  • 可选参数:当请求参数不是必需的,可以为注解指定一个默认值
  • 数据转化:Spring可以自动将请求参数转换为相应的数据类型
  • 数据和集合:可以绑定请求参数到数组或集合类型的参数

3. 源码

java 复制代码
package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.ui.Model;

/**
 * Annotation to bind individual request parameters to method parameters.
 * Typically used with {@link RequestMapping} or {@link GetMapping} / {@link PostMapping}.
 *
 * <p>For example, a GET request to "/users?name=John&age=25" could be handled as follows:
 *
 * <pre class="code">
 * &#64;GetMapping("/users")
 * public String handleRequest(&#64;RequestParam("name") String name,
 *                             &#64;RequestParam("age") int age,
 *                             Model model) {
 *     model.addAttribute("name", name);
 *     model.addAttribute("age", age);
 *     return "userView";
 * }
 * </pre>
 *
 * <p>This annotation may be used as a method parameter, to bind to a single request parameter,
 * or as a method return value, to bind to all request parameters in a {@link Model}.
 *
 * @author Arjen Poutsma
 * @since 3.0
 */
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
    /**
     * The name of the request parameter to bind to.
     */
    // String 类型的属性,指定URL中参数的名称
    String value() default "";
    
    /**
     * @since 4.2
     */
    @AlisaFor("value")
    // Spring4.2版本 开始提供的String类型的属性,与name属性作用相同。
    String name() default "";

    /**
     * Whether the request parameter is required.
     */
    // boolean类型的属性,指定对应的参数是否必须有值;
    // true, 必须有值
    // false: 可以没有值
    // 如果为true时,参数没有值就会报错
    boolean required() default true;

    /**
     * The default value to use if the request parameter is not provided.
     */
    // String类型的属性,指定参数没有值时的默认值。
    String defaultValue() default ValueConstants.DEFAULT_NONE;
}

4. Demo

java 复制代码
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class ProductController {

    @GetMapping("/products")
    public List<Product> searchProducts(
            @RequestParam(value = "category", required = false, defaultValue = "all") String category,
            @RequestParam(value = "minPrice", required = false, defaultValue = "0") Double minPrice,
            @RequestParam(value = "maxPrice", required = false, defaultValue = "1000000") Double maxPrice) {
        
        // 调用服务层方法,根据参数搜索产品
        return productService.search(category, minPrice, maxPrice);
    }
}
java 复制代码
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class CourseController {

    @GetMapping("/search-courses")
    public List<Course> searchCourses(
            @RequestParam(value = "courseName", required = false) String courseName,
            @RequestParam(value = "teacherName", required = false) String teacherName,
            @RequestParam(value = "difficulty", required = false, defaultValue = "all") String difficulty) {
        
        // 调用服务层方法,根据参数搜索课程
        return courseService.searchCourses(courseName, teacherName, difficulty);
    }
}
相关推荐
小时候的阳光1 小时前
SpringBoot3 spring.factories 自动配置功能不生效?
spring boot·spring·失效·factories·imports
ytttr8732 小时前
matlab通过Q学习算法解决房间路径规划问题
学习·算法·matlab
张小洛3 小时前
Spring IOC容器核心阶段解密:★Bean实例化全流程深度剖析★
java·后端·spring·ioc容器·bean实例化
寻丶幽风3 小时前
论文阅读笔记——NoPoSplat
论文阅读·笔记·三维重建·3dgs·相机位姿·dustr
非ban必选4 小时前
spring-ai-alibaba官方 Playground 示例
java·人工智能·spring
听风ツ5 小时前
固高运动控制
学习
要开心吖ZSH5 小时前
《Spring 中上下文传递的那些事儿》Part 2:Web 请求上下文 —— RequestContextHolder 与异步处理
java·spring
西岭千秋雪_5 小时前
Redis缓存架构实战
java·redis·笔记·学习·缓存·架构
XvnNing5 小时前
【Verilog硬件语言学习笔记4】FPGA串口通信
笔记·学习·fpga开发
海棠蚀omo5 小时前
C++笔记-位图和布隆过滤器
开发语言·c++·笔记