Springboot 3.需求携带参数的get请求

本文详细介绍了如何使用Spring MVC处理Cookies,并演示了两种GET请求的实现方式:一种通过URL参数传递,另一种通过路径变量获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 还是拿来上节讲的代码:

package com.course.server;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController    //被告诉我是你需要扫描的类
public class MyGetMethod {

    @RequestMapping(value = "/getCookies",method = RequestMethod.GET)    //访问的路径是什么
    public String getCookies(HttpServletResponse response){
        //HttpServerletRequest    装请求信息
        //HttpServerletResponse   装响应信息
        Cookie cookie = new Cookie("login","ture");
        response.addCookie(cookie);

        return "恭喜你获得cookies信息成功";
    }

    @RequestMapping(value = "/get/with/cookies",method = RequestMethod.GET)
    public String getWithCookies(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(Objects.isNull(cookies)){
            return "你必须携带cookies信息来";
        }

        for(Cookie cookie : cookies){
            if(cookie.getName().equals("login") && cookie.getName().equals("true")){
                return "恭喜你访问成功";
            }
        }
        return "你必须携带cookies信息来";
    }

    /**
    * 开发一个需要携带参数才能访问的get请求
    * 第一种实现方式是 url: ip:port/get/with/param?key=value&key=value
    * 模拟获取商品列表  开始页数,结束的页数,一页20条数据
    * */

    //第一种需要携带参数访问的get请求,将参数定义在方法传参位置处,用@RequestParam关键字,在浏览器地址栏中传入
    @RequestMapping(value = "/get/with/param",method = RequestMethod.GET)  //请求的url
    public Map<String,Integer> getList(@RequestParam Integer start,
                                       @RequestParam Integer end){
        Map<String,Integer> myList = new HashMap<>();
        myList.put("鞋",400);
        myList.put("衬衫",300);
        myList.put("干脆面",1);

        return myList;

    }

    /**
     *第2种需要携带参数访问的get请求,用到的是@PathVariable 关键字,因为是穿的路径
     * url:  ip:port/get/with/param/10/20
     * */

    @RequestMapping(value = "/get/with/param/{start}/{end}")  //另一种请求url
    public Map myGetList(@PathVariable Integer start,
                         @PathVariable Integer end){

        Map<String,Integer> myList = new HashMap<>();
        myList.put("鞋",400);
        myList.put("衬衫",300);
        myList.put("干脆面",1);

        return myList;
    }

}

访问的两种方式:

 

转载于:https://www.cnblogs.com/peiminer/p/9675947.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值