写入cookies:
package com.tsinghuas;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class CookieTest1 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res){
try{
res.setContentType("text/html;charset=gbk");
PrintWriter pw = res.getWriter();
//
Cookie myCookie = new Cookie("color1","red");
myCookie.setMaxAge(30);
res.addCookie(myCookie);
pw.println("已经创建了cookie");
}catch(Exception e){
e.printStackTrace();
}
finally{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res){
this.doGet(req,res);
}
}
从cookies中读取
package com.tsinghuas;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class CookieTest2 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res){
try{
res.setContentType("text/html;charset=gbk");
PrintWriter pw = res.getWriter();
Cookie[] allCookies=req.getCookies();
int i=0;
if(allCookies!=null){
for(i=0;i<allCookies.length;i++){
Cookie temp = allCookies[i];
if(temp.getName().equals("color1")){
String val = temp.getValue();
pw.println("color1="+val);
break;
}
}
if(allCookies.length==i){
pw.println("cookie 过期");
}
}else{
pw.println("不存在cookie,或者过期");
}
}catch(Exception e){
e.printStackTrace();
}
finally{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res){
this.doGet(req,res);
}
}