首先要有一個啟動類,默認的啟動類的名字就是Application.java。啟動的時候直接右鍵點擊run就可以
Application.java:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan("com.course.server") //需要掃描的包 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
新建一個類,為了驗證get接口測試
MyGetMethod.java
package com.course.server; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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"); //定義一個cookies信息 response.addCookie(cookie); return "恭喜你獲得cookies信息成功"; }
@RequestMapping(value = "/get/with/cookies",method = RequestMethod.GET)
public String getWithCookies(HttpServletRequest request){
Cookie[] cookies = request.getCookies(); //從請求中獲取cookies信息
if(Objects.isNull(cookies)){
return "你必須攜帶cookies信息來";
}
for(Cookie cookie : cookies){
if(cookie.getName().equals("login") && cookie.getName().equals("true")){
return "恭喜你訪問成功";
}
}
return "你必須攜帶cookies信息來";
}
}
然后,啟動服務,右鍵點擊Application,會啟動服務,會出現控制台的start
然后,直接去瀏覽器,輸入localhost:8888/getCookies (這是響應有了cookie 信息) 因為上一節已經寫了配置的端口是8888
第二個方法是請求中呆着cookies,那么用jmeter來訪問
添加一個線程組,添加一個HTTP Cookie管理器,填入cookie信息:
添加一個http請求,填入信息,添加一個查看結果樹:
運行以后:會看到cookies信息和響應數據,證明請求成功