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);
    }
}
相关推荐
东方芷兰3 小时前
伯克利 CS61A 课堂笔记 11 —— Mutability
笔记·python
快下雨了L8 小时前
C++面试笔记(持续更新...)
笔记
White graces8 小时前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea
陈无左耳、9 小时前
HarmonyOS学习第3天: 环境搭建开启鸿蒙开发新世界
学习·华为·harmonyos
柃歌9 小时前
【UCB CS 61B SP24】Lecture 7 - Lists 4: Arrays and Lists学习笔记
java·数据结构·笔记·学习·算法
JANGHIGH9 小时前
c++ std::list使用笔记
c++·笔记·list
柃歌9 小时前
【UCB CS 61B SP24】Lecture 4 - Lists 2: SLLists学习笔记
java·数据结构·笔记·学习·算法
是姜姜啊!9 小时前
redis的应用,缓存,分布式锁
java·redis·spring
大溪地C10 小时前
Git 合并冲突解决与状态分析笔记
笔记·git
虾球xz10 小时前
游戏引擎学习第115天
学习·游戏引擎