springboot系列九: 接收参数相关注解

news2024/9/23 19:27:24

文章目录

  • 基本介绍
  • 接收参数相关注解应用实例
      • @PathVariable
      • @RequestHeader
      • @RequestParam
      • @CookieValue
      • @RequestBody
      • @RequestAttribute
      • @SessionAttribute
  • 复杂参数
    • 基本介绍
    • 应用实例
  • 自定义对象参数-自动封装
    • 基本介绍
    • 应用实例

在这里插入图片描述


⬅️ 上一篇: springboot系列八: springboot静态资源访问,Rest风格请求处理


🎉 欢迎来到 springboot系列九: 接收参数相关注解 🎉

在本篇文章中,我们将探讨 Spring Boot 中接收参数的相关注解。通过学习这些注解,您可以更灵活地处理客户端传递的参数,从而提高开发效率。


🔧 本篇需要用到的项目:


基本介绍

1.SpringBoot 接收客户端提交数据 / 参数会使用到相关注解.

2.详细学习 @PathVariable, @RequestHeader, @ModelAttribute, @RequestParam, @CookieValue, @RequestBody

接收参数相关注解应用实例

●需求:
演示各种方式提交数据/参数给服务器, 服务器如何使用注解接收

@PathVariable

1.创建src/main/resources/public/index.html
JavaWeb系列十: web工程路径专题

<h1>跟着老韩学springboot</h1>
基本注解:
<hr/>
<!--
    1. web工程路径知识:
    2. / 会解析成 http://localhost:8080
    3. /monster/100/king => http://localhost:8080/monster/100/king
    4. 如果不带 /, 会以当前路径为基础拼接
/-->
<a href="/monster/100/king">@PathVariable-路径变量 monster/100/king</a><br/><br/>
</body>

2.创建src/main/java/com/zzw/springboot/controller/ParameterController.java
url占位符回顾

@RestController
public class ParameterController {

    /**
     * 1./monster/{id}/{name} 构成完整请求路径
     * 2.{id} {name} 就是占位变量
     * 3.@PathVariable("name"): 这里 name 和 {name} 命名保持一致
     * 4.String name_ 这里自定义, 这里韩老师故意这么写
     * 5.@PathVariable Map<String, String> map 把所有传递的值传入map
     * 6.可以看下@pathVariable源码
     * @return
     */
    @GetMapping("/monster/{id}/{name}")
    public String pathVariable(@PathVariable("id") Integer id,
                               @PathVariable("name") String name,
                               @PathVariable Map<String, String> map) {
        System.out.println("id = " + id + "\nname = " + name + "\nmap = " + map);
        return "success";
    }
}

3.测试 http://localhost:8088/monster/100/king

在这里插入图片描述
在这里插入图片描述

@RequestHeader

需求: 演示@RequestHeader使用.

1.修改src/main/resources/public/index.html

<a href="/requestHeader">@RequestHeader-获取http请求头</a><br/><br/>

2.修改ParameterController.java
JavaWeb系列八: WEB 开发通信协议(HTTP协议)

/**
 * 1. @RequestHeader("Cookie") 获取http请求头的 cookie信息
 * 2. @RequestHeader Map<String, String> header 获取到http请求的所有信息
 */
@GetMapping("/requestHeader")
public String requestHeader(@RequestHeader("Host") String host,
                            @RequestHeader Map<String, String> header) {
    System.out.println("host = " + host + "\nheader = " + header);
    return "success";
}

3.测试

在这里插入图片描述
在这里插入图片描述

@RequestParam

需求: 演示@RequestParam使用.

1.修改src/main/resources/public/index.html

<a href="/hi?name=赵志伟&fruit=apple&fruit=pear&address=上海&id=3">@RequestParam-获取请求参数</a><br/><br/>

2.修改ParameterController.java
SpringMVC系列五: SpringMVC映射请求数据

/**
 * 如果我们希望将所有的请求参数的值都获取到, 可以通过
 * @RequestParam Map<String, String> params
 */
@GetMapping("/hi")
public String hi(@RequestParam(value = "name") String username,
                 @RequestParam(value = "fruit") List<String> fruits,
                 @RequestParam Map<String, String> params) {
    System.out.println("username = " + username + "\nfruits = "
            + fruits + "\nparams = " + params);
    return "success";
}

3.测试

在这里插入图片描述
在这里插入图片描述

@CookieValue

需求: 演示@CookieValue使用.

1.修改src/main/resources/public/index.html

<a href="/cookie">@CookieValue-获取cookie值</a>

2.修改ParameterController.java
JavaWeb系列十一: Web 开发会话技术(Cookie, Session)

/**
 * 因为我们的浏览器目前没有cookie, 我们可以自己设置cookie
 * 如果要测试, 可以先写一个方法, 在浏览器创建对应的cookie
 * 说明:
 * 1. value = "cookie_key" 表示接收名字为 cookie_key的cookie
 * 2. 如果浏览器携带来对应的cookie, 那么后面的参数是String, 则接收到的是对应的value
 * 3. 后面的参数是Cookie, 则接收到的是封装好的对应的cookie
 */
@GetMapping("/cookie")
public String cookie(@CookieValue(value = "cookie_key") String cookie_value,
                     @CookieValue(value = "username") Cookie cookie,
                     HttpServletRequest request) {
    System.out.println("cookie_value = " + cookie_value
            + "\nusername = " + cookie.getName() + "-" + cookie.getValue());
    Cookie[] cookies = request.getCookies();
    
    for (Cookie cookie1 : cookies) {
        System.out.println("cookie1 = " + cookie1.getName() + "-" + cookie1.getValue());
    }
    return "success";
}

3.测试
在这里插入图片描述
在这里插入图片描述

@RequestBody

需求: 演示@RequestBody使用.

1.修改src/main/resources/public/index.html

<h1>测试@RequestBody获取数据: 获取POST请求体</h1>
<form action="/save" method="post">
    名字: <input type="text" name="name"><br/>
    年龄: <input type="text" name="age"><br/>
    <input type="submit" value="提交"/>
</form>

2.修改ParameterController.java
SpringMVC系列十: 中文乱码处理与JSON处理

/**
 * @RequestBody 是整体取出Post请求内容
 */
@PostMapping("/save")
public String postMethod(@RequestBody String content) {
    System.out.println("content = " + content);//content = name=zzw&age=23
    return "sucess";
}

3.测试

在这里插入图片描述

content = name=zzw&age=123

@RequestAttribute

需求: 演示@RequestAttribute使用. 获取request域的属性.

1.修改src/main/resources/public/index.html

<a href="/login">@RequestAttribute-获取request域属性</a>

2.创建RequestController.java
SpringMVC系列十: 中文乱码处理与JSON处理

@Controller
public class RequestController {
    @RequestMapping("/login")
    public String login(HttpServletRequest request) {
        request.setAttribute("user", "赵志伟");//向request域中添加的数据
        return "forward:/ok";//请求转发到 /ok
    }

    @GetMapping("/ok")
    @ResponseBody
    public String ok(@RequestAttribute(value = "user", required = false) String username,
                     HttpServletRequest request) {
        //获取到request域中的数据
        System.out.println("username--" + username);
        System.out.println("通过servlet api 获取 username-" + request.getAttribute("user"));
        return "success"; //返回字符串, 不用视图解析器
    }
}

3.测试…

@SessionAttribute

需求: 演示@SessionAttribute使用. 获取session域的属性.

1.修改src/main/resources/public/index.html

<a href="/login">@SessionAttribute-获取session域属性</a>

2.创建RequestController.java
JavaWeb系列十一: Web 开发会话技术(Cookie, Session)

@Controller
public class RequestController {
    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpSession session) {
        request.setAttribute("user", "赵志伟");//向request域中添加的数据
        session.setAttribute("mobile", "黑莓");//向session域中添加的数据
        return "forward:/ok";//请求转发到 /ok
    }

    @GetMapping("/ok")
    @ResponseBody
    public String ok(@RequestAttribute(value = "user", required = false) String username,
                     HttpServletRequest request,
                     @SessionAttribute(value = "mobile", required = false) String mobile,
                     HttpSession session) {
        //获取到request域中的数据
        System.out.println("username--" + username);
        System.out.println("通过servlet api 获取 username-" + request.getAttribute("user"));

        //获取session域中的数据
        System.out.println("mobile--" + mobile);
        System.out.println("通过HttpSession 获取 mobile-" + session.getAttribute("mobile"));
        return "success"; //返回字符串, 不用视图解析器
    }
}

3.测试…

复杂参数

基本介绍

1.在开发中, SpringBoot在相应客户端请求时, 也支持复杂参数

2.Map, Model, Errors/BindingResult, RedirectAttributes, ServletResponse, SessionStatus, UriComponentsBuilder, ServletUriComponentBuilder, HttpSession.

3.Map, Model,数据会被放在request域, 到时Debug一下.

4.RedirectAttribute 重定向携带数据

应用实例

说明: 演示复杂参数的使用.
重点: Map, Model, ServletResponse

●代码实现
1.修改src/main/java/com/zzw/springboot/controller/RequestController.java
SpringMVC系列六: 模型数据

//响应一个注册请求
@GetMapping("/register")
public String register(Map<String, Object> map,
                       Model model,
                       HttpServletRequest request) {
    //如果一个注册请求, 会将注册数据封装到map或者model
    //map中的数据和model中的数据, 会被放入到request域中
    map.put("user", "赵志伟");
    map.put("job", "java");
    model.addAttribute("sal", 6000);
    //一会我们再测试response使用
    
    //请求转发
    return "forward:/registerOk";
}

@GetMapping("/registerOk")
@ResponseBody
public String registerOk(HttpServletRequest request,
                         @RequestAttribute("user") String user,
                         @RequestAttribute("job") String job,
                         @RequestAttribute("sal") Double sal) {
    System.out.println("user=" + request.getAttribute("user"));
    System.out.println("job=" + job);
    System.out.println("sal=" + sal);
    return "success";
}

2.浏览器输入 http://localhost:8088/register , 打断点测试

SpringMVC系列十三: SpringMVC执行流程 - 源码分析

在这里插入图片描述

进入目标方法

在这里插入图片描述

剖析 request 对象

在这里插入图片描述

3.继续修改 register()方法
JavaWeb系列十一: Web 开发会话技术(Cookie, Session)

//响应一个注册请求
@GetMapping("/register")
public String register(Map<String, Object> map,
                       Model model,
                       HttpServletRequest request,
                       HttpServletResponse response) throws UnsupportedEncodingException {
    //如果一个注册请求, 会将注册数据封装到map或者model
    //map中的数据和model中的数据, 会被放入到request域中
    map.put("user", "赵志伟");
    map.put("job", "java");
    model.addAttribute("sal", 6000);
    //一会我们再测试response使用
    //演示创建cookie, 并通过response 添加到浏览器/客户端
    Cookie cookie = new Cookie("email", "978964140@qq.com");
    response.addCookie(cookie);

    //请求转发
    return "forward:/registerOk";
}

4.测试

在这里插入图片描述

自定义对象参数-自动封装

基本介绍

1.在开发中, SpringBoot在响应客户端/浏览器请求时, 也支持自定义对象参数

2.完成自动类型转换与格式化

3.支持级联封装

应用实例

●需求说明:
演示自定义对象参数使用,完成自动封装,类型转换。

●代码实现
1.创建public/save.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加妖怪</title>
</head>
<body>
<form action="?" method="?">
    编号: <input name="" value=""><br/>
    姓名: <input name="" value=""><br/>
    年龄: <input name="" value=""><br/>
    婚否: <input name="" value=""><br/>
    生日: <input name="" value=""><br/>
    坐骑名称: <input name="" value=""><br/>
    坐骑价格: <input name="" value=""><br/>
    <input type="submit" value="保存"/>
</form>
</body>
</html>

2.创建src/main/java/com/zzw/springboot/bean/Car.java

@Data
public class Car {
    private String name;
    private Double price;
}

3.创建src/main/java/com/zzw/springboot/bean/Monster.java

@Data
public class Monster {
    private Integer id;
    private String name;
    private Integer age;
    private Boolean maritalStatus;
    private Date birthday;
    private Car car;
}

4.修改ParameterController.java

//处理添加monster的方法
@PostMapping("/saveMonster")
public String saveMonster(Monster monster) {
    System.out.println("monster = " + monster);
    return "success";
}

5.回填public/save.html

<form action="saveMonster" method="post">
    编号: <input name="id" value="100"><br/>
    姓名: <input name="name" value="张三"><br/>
    年龄: <input name="age" value="30"><br/>
    婚否: <input name="maritalStatus" value="未婚"><br/>
    生日: <input name="birthday" value="1994-01-01"><br/>
    <input type="submit" value="保存"/>
</form>

6.自动封装需要用到自定义转换器. 接下来, 继续学习自定义转换器.


🔜 下一篇预告: springboot系列十: 自定义转换器,处理JSON,内容协商


📚 目录导航 📚

  1. springboot系列一: springboot初步入门
  2. springboot系列二: sprintboot依赖管理
  3. springboot系列三: sprintboot自动配置
  4. springboot系列四: sprintboot容器功能
  5. springboot系列五: springboot底层机制实现 上
  6. springboot系列六: springboot底层机制实现 下
  7. springboot系列七: Lombok注解,Spring Initializr,yaml语法
  8. springboot系列八: springboot静态资源访问,Rest风格请求处理
  9. springboot系列九: 接收参数相关注解
  10. springboot系列十: 自定义转换器,处理JSON,内容协商

💬 读者互动 💬
在学习 Spring Boot 接收参数相关注解的过程中,您有哪些新的发现或疑问?欢迎在评论区留言,让我们一起讨论吧!😊


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1929781.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

02-Redis未授权访问漏洞

免责声明 本文仅限于学习讨论与技术知识的分享&#xff0c;不得违反当地国家的法律法规。对于传播、利用文章中提供的信息而造成的任何直接或者间接的后果及损失&#xff0c;均由使用者本人负责&#xff0c;本文作者不为此承担任何责任&#xff0c;一旦造成后果请自行承担&…

【Windows】Microsoft PC Manager

使用 Microsoft PC Manager&#xff0c;用户可以轻松执行基本的计算机维护&#xff0c;并通过一键操作提升设备速度。这款应用程序提供了一系列功能&#xff0c;包括磁盘清理、启动应用管理、病毒扫描、Windows 更新检查、进程监控和存储管理。 Microsoft PC Manager 的关键特…

React学习笔记03-----手动创建和运行

一、项目创建与运行【手动】 react-scripts集成了webpack、bable、提供测试服务器 1.目录结构 public是静态目录&#xff0c;提供可以供外部直接访问的文件&#xff0c;存放不需要webpack打包的文件&#xff0c;比如静态图片、CSS、JS src存放源码 &#xff08;1&#xff09…

xss复习总结及ctfshow做题总结xss

xss复习总结 知识点 1.XSS 漏洞简介 ​ XSS又叫CSS&#xff08;Cross Site Script&#xff09;跨站脚本攻击是指恶意攻击者往Web页面里插入恶意Script代码&#xff0c;当用户浏览该页之时&#xff0c;嵌入其中Web里面的Script代码会被执行&#xff0c;从而达到恶意攻击用户的…

ASF平台

最近一直在研究滑坡&#xff0c;但是insar数据处理很麻烦&#xff0c;自己手动处理gamma有很慢&#xff0c;而且据师兄说&#xff0c;gamma处理还很看经验&#xff0c;我就又去看了很多python库和其他工具: isce mintpy pyint 也使用了asf上面的处理产品&#xff0c;虽然也…

H. Beppa and SwerChat【双指针】

思路分析&#xff1a;运用双指针从后往前扫一遍&#xff0c;两次分别记作数组a&#xff0c;b&#xff0c;分别使用双指针i和j来扫&#xff0c;如果一样就往前&#xff0c;如果不一样&#xff0c;i–,ans #include<iostream> #include<cstring> #include<string…

C#绘制含流动块的管道

1&#xff0c;效果。 2&#xff0c;绘制技巧。 1&#xff0c;流动块的实质是使用Pen的自定义DashStyle绘制的线&#xff0c;并使用线的偏移值呈现出流动的效果。 Pen barPen new Pen(BarColor, BarHeight);barPen.DashStyle DashStyle.Custom;barPen.DashOffset startOffse…

解读InnoDB数据库索引页与数据行的紧密关联

目录 一、快速走进索引页结构 &#xff08;一&#xff09;整体展示说明 &#xff08;二&#xff09;内容说明 File Header&#xff08;文件头部&#xff09; Page Header&#xff08;页面头部&#xff09; Infimum Supremum&#xff08;最小记录和最大记录&#xff09; …

太速科技-FMC207-基于FMC 两路QSFP+光纤收发子卡

FMC207-基于FMC 两路QSFP光纤收发子卡 一、板卡概述 本卡是一个FPGA夹层卡&#xff08;FMC&#xff09;模块&#xff0c;可提供高达2个QSFP / QSFP 模块接口&#xff0c;直接插入千兆位级收发器&#xff08;MGT&#xff09;的赛灵思FPGA。支持利用Spartan-6、Virtex-6、Kin…

Webpack看这篇就够了

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 非常期待和您一起在这个小…

java.sql.SQLException: Unknown system variable ‘query_cache_size‘【Pyspark】

1、问题描述 学习SparkSql中&#xff0c;将spark中dataframe数据结构保存为jdbc的格式并提交到本地的mysql中&#xff0c;相关代码见文章末尾。 运行代码时报出相关配置文件错误&#xff0c;如下。 根据该报错&#xff0c;发现网络上多数解决方都是基于java开发的解决方案&a…

GPT-4从0到1搭建一个Agent简介

GPT-4从0到1搭建一个Agent简介 1. 引言 在人工智能领域&#xff0c;Agent是一种能够感知环境并采取行动以实现特定目标的系统。本文将简单介绍如何基于GPT-4搭建一个Agent。 2. Agent的基本原理 Agent的核心是感知-行动循环&#xff08;Perception-Action Loop&#xff09;…

【Windows】系统盘空间不足?WizTree 和 DISM++ 来帮忙

当您的系统盘空间接近饱和时&#xff0c;了解硬盘空间的使用情况变得尤为重要。在这种情况下&#xff0c;您可以利用 Windows 内置的存储使用工具来快速查看哪些文件和应用程序占用了大量空间&#xff0c;并采取相应措施进行清理。此外&#xff0c;第三方工具如 WizTree 可以提…

Java NIO合并多个文件

NIO API java.nio (Java Platform SE 8 ) 直接上代码 package com.phil.aoplog.util;import lombok.extern.slf4j.Slf4j;import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel;Slf4j public…

勒索防御第一关 亚信安全AE防毒墙全面升级 勒索检出率提升150%

亚信安全信舷AE高性能防毒墙完成能力升级&#xff0c;全面完善勒索边界“全生命周期”防御体系&#xff0c;筑造边界勒索防御第一关&#xff01; 勒索之殇&#xff0c;银狐当先 当前勒索病毒卷携着AI技术&#xff0c;融合“数字化”的运营模式&#xff0c;形成了肆虐全球的网…

数据结构进阶:使用链表实现栈和队列详解与示例(C, C#, C++)

文章目录 1、 栈与队列简介栈&#xff08;Stack&#xff09;队列&#xff08;Queue&#xff09; 2、使用链表实现栈C语言实现C#语言实现C语言实现 3、使用链表实现队列C语言实现C#语言实现C语言实现 4、链表实现栈和队列的性能分析时间复杂度空间复杂度性能特点与其他实现的比较…

VBA学习(21):遍历文件夹(和子文件夹)中的文件

很多时候&#xff0c;我们都想要遍历文件夹中的每个文件&#xff0c;例如在工作表中列出所有文件名、对每个文件进行修改。VBA给我们提供了一些方式&#xff1a;&#xff08;1&#xff09;Dir函数&#xff1b;&#xff08;2&#xff09;File System Object。 使用Dir函数 Dir…

31.RAM-IP核的配置、调用、仿真全流程

&#xff08;1&#xff09;RAM IP核简介 RAM是随机存取存储器&#xff08;Random Access Memory&#xff09;的简称&#xff0c;是一个易失性存储器&#xff0c;其工作时可以随时对任何一个指定地址写入或读出数据。&#xff08;掉电数据丢失&#xff09; &#xff08;2&#…

Spring Cloud Gateway 入门与实战

一、网关 在微服务框架中&#xff0c;网关是一个提供统一访问地址的组件&#xff0c;它充当了客户端和内部微服务之间的中介。网关主要负责流量路由和转发&#xff0c;将外部请求引导到相应的微服务实例上&#xff0c;同时提供一些功能&#xff0c;如身份认证、授权、限流、监…

【企业级监控】Zabbix监控MySQL主从复制

Zabbix自定义监控项与触发器 文章目录 Zabbix自定义监控项与触发器资源列表基础环境前言四、监控MySQL主从复制4.1、部署mysql主从复制4.1.1、在两台主机&#xff08;102和103上安装&#xff09;4.1.2、主机102当master4.1.3、主机103当slave 4.2、MySQL-slave端开启自定义Key值…