cookie使用及注意要点


 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);
}

猜你喜欢

转载自blog.csdn.net/weixin_41868360/article/details/80862452