【SpringBoot】请求处理——常用参数注释及使用

一、基本注释测试代码
<form action="/save" method="post">
    测试@RequestBody 获取数据 <br/>
    用户名: <input name="username"> <br>
    邮箱:<input name="email">
    <input type="submit" value="提交">
</form>
测试基本注释 ---- queryString 查询字符串 @RequestParam <br>
<a href="/car/1/owner/liuwanqing?age=18&interes=coding&interes=reading">/car/{id}/owner/{username}</a>
二、Controller类整体代码
package com.example.demo.controller;

import org.apache.tomcat.util.http.parser.Cookie;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ParameterTestController {

    @GetMapping("/car/{id}/owner/{name}")
    public Map<String, Object> getCar(@PathVariable Integer id, @PathVariable String name, @PathVariable Map<String, String> pv,
                                      @RequestHeader("user-agent") String userAgent, @RequestHeader Map<String, String> headers,
                                      @RequestParam("age")int age, @RequestParam("interes") List<String> list,
                                      @RequestParam Map<String, String> all,
                                      @CookieValue("Idea-be57cbfa") String coS,
                                      @CookieValue("Idea-be57cbfa") Cookie cookie
                                      ){
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("username", name);
        map.put("pv", pv);
        map.put("userAgent", userAgent);
        map.put("headers", headers);
        map.put("age", age);
        map.put("interes", list);
        map.put("all", all);
        map.put("cookie", coS);
        System.out.println(cookie.getClass());
        return map;
    }

    // 获取请求体
    @RequestMapping("/save")
    public Map postMethod(@RequestBody String content){
        Map<String, Object> map = new HashMap<>();
        map.put("content", content);
        return map;
    }

    // SpringBoot默认禁用矩阵变量功能
    // 手动开启:
    @GetMapping("/cars/{path}")
    public Map carsSell(@MatrixVariable("low") Integer low, @MatrixVariable("brand") List<String> brand, @PathVariable("path") String path){
        Map<String, Object> map = new HashMap<>();
        map.put("low", low);
        map.put("brand", brand);
        map.put("path", path);
        return map;
    }
    // boss/1;age=20/2;age=10
    @GetMapping("/boss/{bossId}/{empId}")
    public Map boss(@MatrixVariable(value = "age", pathVar = "bossId") Integer ageBoss, @MatrixVariable(value = "age", pathVar = "empId") Integer empAge){
        Map<String, Object> map = new HashMap<>();
        map.put("bossAge" , ageBoss);
        map.put("empAge", empAge);
        return map;
    }
}
三、各注释详细解释
1. @GetMapping("/car/{id}/owner/{name}")

1. 取出路径中的变量——id及name

(1) 方法一:使用 @PathVariable 注释, 注意变量名要与GetMapping中定义的相同

@PathVariable Integer id, @PathVariable String name

(2)方法二:使用 @PathVariable Map<String, String> pv取出所有

@PathVariable Map<String, String> pv

执行结果截图:
在这里插入图片描述


2、得到请求头
(1)方法一: 使用 @RequestHeader(“请求头名”) 得到某个请求的值

RequestHeader("user-agent") String userAgent

(2)方法二: 使用 @RequestHeader Map<String, String> headers 得到所有请求头的哈希表

@RequestHeader Map<String, String> headers

执行结果截图:
在这里插入图片描述


3. 取出查询字符串queryString
—— 即问号后内容:

/car/1/owner/liuwanqing?age=18&interes=coding&interes=reading

(1)方法一:@RequestParam(“变量名”)

 @RequestParam("age")int age, @RequestParam("interes") List<String> list

(2)方法二:@RequestParam Map<String, String> all 得到所有

@RequestParam Map<String, String> all

执行结果截图:
在这里插入图片描述


4. 取出Cookie的值
(1)方法一:@CookieValue(“Idea-be57cbfa”) String coS
(2)方法二:@CookieValue(“Idea-be57cbfa”) Cookie cookie


5、获取表单数据
使用 @RequestBody 注释

 // 获取请求体
    @RequestMapping("/save")
    public Map postMethod(@RequestBody String content){
        Map<String, Object> map = new HashMap<>();
        map.put("content", content);
        return map;
    }

表单:

<form action="/save" method="post">
    测试@RequestBody 获取数据 <br/>
    用户名: <input name="username"> <br>
    邮箱:<input name="email">
    <input type="submit" value="提交">
</form>

执行结果:
在这里插入图片描述


6、矩阵变量的使用
访问方式:
/car/{path; low=34; brand=byd, audi, yd}
问题:页面开发,cookie禁用了,session里面的内容怎么使用
1、session.set(a, b) ----> jsessionid ----> cookies ----> 每次发请求携带
2、url重写: /abc; jsessionid=xxxxx 把cookie的值按矩阵变量的方式传递
矩阵变量使用方法
(1)开启矩阵变量的使用:SpringBoot会默认删除分号;后内容
a. 实现WebMvcConfigurer类,重写configurePathMatch方法
b.注册 WebMvcConfigurer容器,改写configurePathMatch

   public void configurePathMatch(PathMatchConfigurer configurer){
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        // 不移除分号;后面的内容,矩阵变量功能就可以生效
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }

    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return  new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                // 不移除分号;后面的内容,矩阵变量功能就可以生效
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }
        };
    }

(2)使用 @MatrixVariable(“”) 方法得到矩阵变量的值

@GetMapping("/cars/{path}")
    public Map carsSell(@MatrixVariable("low") Integer low, @MatrixVariable("brand") List<String> brand, @PathVariable("path") String path){
        Map<String, Object> map = new HashMap<>();
        map.put("low", low);
        map.put("brand", brand);
        map.put("path", path);
        return map;
    }
    // boss/1;age=20/2;age=10
    @GetMapping("/boss/{bossId}/{empId}")
    public Map boss(@MatrixVariable(value = "age", pathVar = "bossId") Integer ageBoss, @MatrixVariable(value = "age", pathVar = "empId") Integer empAge){
        Map<String, Object> map = new HashMap<>();
        map.put("bossAge" , ageBoss);
        map.put("empAge", empAge);
        return map;
    }

执行结果截图:
在这里插入图片描述


7、得到请求属性
方法一: 使用@RequestAttribute(“属性名”)
方法二:使用 HttpServletRequest request 得到请求,再用getAttribute()方法得到属性值

    @GetMapping("/goto")
    public String goToPage(HttpServletRequest request){
        request.setAttribute("msg", "成功");
        request.setAttribute("code", 200);
        //System.out.println(request.getAttribute("msg"));
        return "forward:/success"; // 转发到 /SUCCESS请求
    }

    @ResponseBody
    @GetMapping("/success")
    public Map success(@RequestAttribute("msg")String msg, @RequestAttribute("code")Integer code, HttpServletRequest request){
        Object msg1 = request.getAttribute("msg");
        Map<String, Object> map = new HashMap<>();
        map.put("reqMethod_msg", msg1);
        map.put("annotation_msg", msg);
        //System.out.println(map);
        return map;
    }

执行结果截图:
在这里插入图片描述

Spring Boot常用的注解有以下几个: 1. @SpringBootApplication: 是一个复合注解,包含了@SpringBootApplication、@EnableAutoConfiguration和@ComponentScan这三个注解。@SpringBootConfiguration注解是@Configuration注解的派生注解,用于加载配置文件。 2. @EnableAutoConfiguration: 用于自动配置Spring Boot应用程序的类。它根据项目中添加的依赖和配置信息,自动配置Spring上下文和各种功能。 3. @ComponentScan: 用于自动扫描并注册Spring Bean。它可以指定要扫描的基础包,以查找被@Component、@Service、@Repository和@Controller等注解标记的类,并将它们注册为Spring Bean。 4. @ExceptionHandler: 声明异常处理方法。当控制器中抛出指定的异常时,该方法将被调用来处理异常。 5. 其他常用的注解还包括@RequestParam、@PathVariable、@RequestBody等,用于处理请求参数、路径变量和请求体等。 这些注解是Spring Boot开发中常用的注解,通过使用它们,我们可以方便地配置和管理Spring Boot应用程序。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [SpringBoot 常用注解汇总](https://blog.csdn.net/m0_67401153/article/details/125243438)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [springboot常用注释的讲解](https://download.csdn.net/download/weixin_38678521/12749861)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值