接著上篇文檔 SpringBoot官方demo運行 繼續(xù)研究 返回cookies信息的get接口開發(fā)痒芝。
1.環(huán)境準備
在源代碼包 java文件下面新建包 com.course.server,包下面新建 MyGetMethod.java文件。
MyGetMethod 方法上方引用 @RestController
2.獲取cookies信息
創(chuàng)建方法 getCookies 复局,方法如下
@RequestMapping(value = "/getCookies",method = RequestMethod.GET)
public String getCookies(HttpServletResponse response){
//HttpServerletRequeat 裝請求信息的類
//HttpServerletResponse 裝響應(yīng)信息的類
Cookie cookie = new Cookie("login","true");
response.addCookie(cookie);
return "恭喜你獲得cookies成功";
}
RequestMapping 對應(yīng)的 value = "/getCookies", 是訪問路徑睬隶,啟動 Application應(yīng)用惭缰。
瀏覽器訪問 http://localhost:8888/getCookies议纯,開發(fā)者工具檢查 cookies信息即可。
3.必須攜帶cookies信息才能訪問的get請求
創(chuàng)建方法 getwithcookies 浅役,方法如下:
@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.getValue().equals("true")) {
return "恭喜你訪問成功";
}
}
return "你必須攜帶cookies信息來";
}
訪問:攜帶cookies信息必須利用工具斩松,postman或者jmeter,添加cookies信息訪問即可。
4.帶參數(shù)的get請求(第一種方法)
創(chuàng)建方法 getlist 觉既,方法如下:
@RequestMapping(value = "/get/with/param",method = RequestMethod.GET)
public Map<String,Integer> getlist(@RequestParam Integer start,
@RequestParam Integer end){
Map<String,Integer> Mylist = new HashMap<>();
Mylist.put("鞋子",500);
Mylist.put("辣條",3);
Mylist.put("書包",400);
return Mylist;
}
訪問: http://localhost:8888//get/with/param?start=10&end=20,則返回Map參數(shù)惧盹。
帶參數(shù)的get請求.png
5.帶參數(shù)的get請求(第二種方法)
創(chuàng)建方法 myGetlist ,方法如下:
@RequestMapping(value = "/get/with/param/{start}/{end}")
public Map<String,Integer> myGetlist(@PathVariable Integer start,
@PathVariable Integer end){
Map<String,Integer> Mylist = new HashMap<>();
Mylist.put("鞋子",500);
Mylist.put("辣條",3);
Mylist.put("書包",400);
return Mylist;
}
訪問:http://localhost:8888//get/with/param/10/20,則返回Map參數(shù)瞪讼。
帶參數(shù)的get請求.png
<完钧椰!>