日期:2014-05-18 浏览次数:20725 次
<%! public static Cookie getCookie(HttpServletRequest request,String name) { Cookie [] cookies =request.getCookies(); if(cookies!=null) { for(int i=0;i<cookies.length;i++) { if(cookies[i].getName().equals(name)) { return cookies[i]; } } } return null; } %> <% //设置cookie //我想把username="heavilyarmed" 和userpwd="123"放到cookie内 //没思路 Cookie nameCookie2=new Cookie("mingzi","nicholas"); nameCookie2.setDomain("http://localhost:1009/twoWeeks"); nameCookie2.setPath("/userinfo"); nameCookie2.setMaxAge(60); response.addCookie(nameCookie2); %> <% //读取 String name="mingzi"; Cookie nameCookie=getCookie(request,name); System.out.println("name is :"+nameCookie.getValue()); System.out.println("thanks"); %>
<%@page pageEncoding="utf-8" %> <%@page import="javax.servlet.http.Cookie" %> <% Cookie nameCookie = new Cookie("username","heavilyarmed"); nameCookie.setMaxAge(60*60);//1小时 response.addCookie(nameCookie); Cookie pwdCookie = new Cookie("userpwd","123"); nameCookie.setMaxAge(60*60);//1小时 response.addCookie(pwdCookie); Cookie[] cookies = request.getCookies(); if( cookies !=null){ for(int i=0;i<cookies.length;i++){ Cookie cookie =cookies[i]; out.println(cookie.getName()+"="+cookie.getValue()); } } %>
------解决方案--------------------
呵呵~~终于搞明白了.
楼主可以这样做:
将cookie作为一个属性放到request中:
request.setAttribute("cookie",nameCookie2);然后再这样取出即可:
Cookie c = (Cookie)request.getAttribute("cookie");
System.out.println(c.getName());
System.out.println(c.getMaxAge());
System.out.println(c.getPath());
这样就可以了~~