存cookie
-
Java code
-
{
-
response.setContentType( " text/html;charset=UTF-8 " );
PrintWriter pw = response.getWriter();
Cookie cookie = new Cookie( " color1 " , " red " ); // 在服务器端创建一个cookie
cookie.setMaxAge( 30 ); // 设置cookie存在时间(按秒计算),如果不设置,则cookie不能保存
response.addCookie(cookie); // 将cookie回写到客户端
pw.println( " 创建了一个cookie " );
}
catch
(Exception e) {
e.printStackTrace();
}
try
取cookie
-
Java code
-
try
{
response.setContentType( " text/html;charset=UTF-8 " );
PrintWriter pw = response.getWriter();
Cookie[] allCookies = request.getCookies(); // 从客户端取得所有的cookie
int i = 0 ;
if (allCookies != null ){
for (i = 0 ; i < allCookies.length; i ++ ) {
Cookie temp = allCookies[i];
if (temp.getName().equals( " color1 " )){
String value = temp.getValue();
pw.println( " color1 = " + value);
break ;
}
}
if (allCookies.length == i) {
pw.println( " Cookie过期啦! " );
}
else
{
pw.println( " 不存在color1或者cookie过期啦 "
);
}
}
}
catch
(Exception e) {
e.printStackTrace();
}