Springboot 3.需求攜帶參數的get請求


 還是拿來上節講的代碼:

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;
    }

}

訪問的兩種方式:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM