一,演示項目的相關信息
1,地址:
https://github.com/liuhongdi/cookietest
2,功能說明:演示mockmvc訪問controller時提交cookie
3,項目結構:如圖:

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest
對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
說明:作者:劉宏締 郵箱: 371125307@qq.com
二,java代碼說明
1,controller/UserController.java
@RestController @RequestMapping("/user") public class UserController { //讀取session @GetMapping("/get") public String getcookie(@CookieValue(value = "username", defaultValue = "") String username) { System.out.println("get cookie:"+username); return "" + username; } //設置session @GetMapping("/set") public String setcookie(@RequestParam("userName")String userName, HttpServletRequest request, HttpServletResponse response) { Cookie cookie = new Cookie("username", userName); //過期時間,單位是:秒(s) cookie.setMaxAge(30 * 24 * 60 * 60); //cookie.setPath(request.getContextPath()); cookie.setPath("/"); response.addCookie(cookie); System.out.println("set cookie:"+userName); return userName; } }
2,controller/UserControllerTest.java
@AutoConfigureMockMvc @SpringBootTest class UserControllerTest { @Autowired private UserController userController; @Autowired private MockMvc mockMvc; @Test @DisplayName("測試讀取cookie值") void getCookie() throws Exception{ Cookie cookieu = new Cookie("username", "mr liu"); //過期時間,單位是:秒(s) cookieu.setMaxAge(30 * 24 * 60 * 60); cookieu.setPath("/"); //query MvcResult mvcResult = mockMvc.perform(get("/user/get") .cookie(cookieu) .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); assertThat(content, equalTo("mr liu")); } @Test @DisplayName("測試讀取cookie值失敗") void getCookieFail() throws Exception{ //query MvcResult mvcResult = mockMvc.perform(get("/user/get") //.cookie(cookieu) .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); assertThat(content, equalTo("")); } @Test @DisplayName("測試寫cookie值") void setCookie() throws Exception{ String cookieValue="laoliu123aaa"; //query MvcResult mvcResult = mockMvc.perform(get("/user/set?userName="+cookieValue) .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); assertThat(content, equalTo(cookieValue)); } }
三,效果測試
1,查接訪問url測試
set cookie:
http://127.0.0.1:8080/user/set?userName=laoliu123
get cookie:
http://127.0.0.1:8080/user/get
返回:

2,執行單元測試:

四,查看spring boot的版本:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.4.3)
