Springboot 3.需求攜帶參數的get請求
阿新 • • 發佈:2018-09-19
代碼 實現 isn getname image framework [] frame sta
還是拿來上節講的代碼:
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; } }
訪問的兩種方式:
Springboot 3.需求攜帶參數的get請求