cookie使用及注意要點
阿新 • • 發佈:2019-01-01
1.新增Cookie
@RequestMapping("/item/{id}") @ResponseBody public ResultVo queryItemDetail(@PathVariable("id")long id, @CookieValue(value="taotao_username",required=false)String username, @CookieValue(value="taotao_password",required=false)String password ) { /*String username = ""; String password = ""; Cookie[] cookies = requset.getCookies(); if(cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if(cookie.getName().equals("taotao_username")) { username = cookie.getValue(); }else if(cookie.getName().equals("taotao_password")) { password = cookie.getValue(); } } }*/ System.out.println("使用者名稱為:"+username); System.out.println("使用者密碼為:"+password); }
常規獲取cookie方式和註解獲取方式
@RequestMapping(value="/list") public void queryCatList(HttpServletResponse response,String callback) throws IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); Cookie nameCookie = new Cookie("taotao_username", "zhangsan"); Cookie pwdCookie = new Cookie("taotao_password", "123456"); nameCookie.setMaxAge(3*24*3600);//設定cookie的過期時間 nameCookie.setDomain("localhost"); nameCookie.setPath("/taotao_rest"); pwdCookie.setMaxAge(3*24*3600);//設定cookie的過期時間 pwdCookie.setDomain("localhost"); pwdCookie.setPath("/taotao_rest"); response.addCookie(nameCookie); response.addCookie(pwdCookie); }