问题一:怎么在java中增加一个cookie;代码:Cookie cookie = new Cookie('mytest','123456'); response.addCookie(cookie);图解:下图中可以看到加入了名为mytest的cookie,它的值为123456。
问题二:怎么在java中修改一个cookie;代码:Cookie[] cookies = request.getCookies();for(Cookie cookie : cookies) { if('mytest'.equals(cookie.getName())) { cookie.setValue('mytestNEW'); response.addCookie(cookie); } }图解:下图中可以看到加入了名为mytest的cookie值已经变为了mytestNEW。
问题三:怎么在java中删除一个cookie;代码:Cookie[] cookies = request.getCookies(); for(Cookie cookie : cookies) { if('mytest'.equals(cookie.getName())) { cookie.setMaxAge(0); response.addCookie(cookie); } }图解:下图中可以看到名为mytest的cookie已经不存在了。
问题四:怎么在java中显示cookie列表;代码:Cookie[] cookies = request.getCookies();for(Cookie cookie : cookies) { try { response.getWriter().println(cookie.getName() + '-->' + cookie.getValue()); } catch (IOException e) { e.printStackTrace(); }}图解:下图中可以看到当前的cookie列表。
问题五:怎么在java中增加一个中文cookie;代码:Cookie cookie; try { cookie = new Cookie('mytest',URLEncoder.encode('我的测试', 'UTF-8')); response.addCookie(cookie); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }图解:下图中可以看到增加了一个名为mytest的Cookie,它的值为浏览器编码后的中文。
问题六:怎么在java中显示中文cookie值;代码:Cookie[] cookies = request.getCookies(); for(Cookie cookie : cookies) { if('mytest'.equals(cookie.getName())) { try { response.getWriter().println(URLDecoder.decode(cookie.getValue(), 'UTF-8')); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}图解:下图中可以看到名为mytest的Cookie值:'我的测试'。
问题七:怎么在java中根据cookie名称获得cookie值;代码:Cookie[] cookies = request.getCookies(); for(Cookie cookie : cookies) { if('mytest'.equals(cookie.getName())) { try { response.getWriter().println(cookie.getName() + '-->' + cookie.getValue()); } catch (IOException e) { e.printStackTrace(); } } }图解:下图中可以看到名为mytest的Cookie。
问题八:怎么在java中设置cookie路径;代码:Cookie cookie1 = new Cookie('mytest','mytest1'); cookie1.setPath('/test1'); Cookie cookie2 = new Cookie('mytest','mytest2'); cookie2.setPath('/test2'); response.addCookie(cookie1); response.addCookie(cookie2);图解:下图中可以看到名为mytest的两个Cookie,它们的内容和路径都不同。注意:不同路径下可以有相同名称的Cookie。
问题九:怎么在java中设置cookie过期时间为60秒;代码:Cookie cookie = new Cookie('mytest','mytest1'); cookie.setMaxAge(60); response.addCookie(cookie);图解:下图中可以看到名为mytest的Cookie,它的过期时间为60秒后。
问题十:怎么在java中设置cookie域名;代码:Cookie cookie = new Cookie('mytest','mytest1'); cookie.setDomain('127.0.0.1'); response.addCookie(cookie);图解:下图中可以看到名为mytest的Cookie,它的主机为127.0.0.1。
问题十一:怎么在java中设置Cookie只有在安全链接(即https)中才有效;代码:Cookie cookie = new Cookie('mytest','mytest1'); cookie.setSecure(true); response.addCookie(cookie);图解:下图中可以看到名为mytest的Cookie,它只限加密连接才能发送。
问题十二:怎么在java中查看cookie版本;代码: Cookie cookie = new Cookie('mytest','mytest1'); try { response.getWriter().println('cookie version-->' + cookie.getVersion()); } catch (IOException e) { e.printStackTrace(); }图解:下图中可以看到名为mytest的Cookie,它的cookie版本是0。