Servlet课程0426(九)Servlet服务器端创建Cookie和客户端读取Cookie

时间:2021-08-20 14:49:56

服务器端创建Cookie:

Win7默认Cookie位置

C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Cookies

CookieTest1.java

//CookieTest1
package com.tsinghua; import javax.servlet.http.*;
import java.io.*; public class CookieTest1 extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)
{ try{ //解决中文乱码
res.setCharacterEncoding("gbk");
PrintWriter pw = res.getWriter();
pw.println("<html>");
//当用户访问该Servlet时,就将信息创建到该用户的cookie中 //1.现在服务器端创建一个cookie
Cookie myCookie = new Cookie("color1","red"); //2.该cookie的存在时间
myCookie.setMaxAge(30);
//如果你不设置存在时间,那么该cookie将不会保存 //3.将该cookie写回到客户端
res.addCookie(myCookie); pw.println("已经创建了cookie"); }
catch(Exception ex)
{
ex.printStackTrace();
} } //处理get请求
//req用于获得客户端(浏览器)的信息
//res用于向 客户端(浏览器)返回信息
public void doPost(HttpServletRequest req, HttpServletResponse res)
{ this.doGet(req,res); } }

客户端读取Cookie

//如何读取Cookie案例
package com.tsinghua; import javax.servlet.http.*;
import java.io.*; public class CookieTest2 extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)
{ try{ //解决中文乱码
res.setCharacterEncoding("gbk");
PrintWriter pw = res.getWriter(); //客户端得到所有cookie信息
Cookie[] allCookies = req.getCookies();
int i = 0;
//如果allCookie不为空
if(allCookies != null)
{
//从中取出cookie
for (i = 0; i<allCookies.length; i++)
{
//依次取出
Cookie temp = allCookies[i]; if(temp.getName().equals("color1"))
{
//得到cookie的值
String val = temp.getValue();
pw.println("color1="+val);
break;
}
}
if(allCookies.length == i)
{
pw.println("cookie过期");
}
}else
{
pw.println("不存在color1这个cookie/或者是过期");
} }
catch(Exception ex)
{
ex.printStackTrace();
} } //处理get请求
//req用于获得客户端(浏览器)的信息
//res用于向 客户端(浏览器)返回信息
public void doPost(HttpServletRequest req, HttpServletResponse res)
{ this.doGet(req,res); } }