JSP-- cookies
当客户端进行了一些操作,比如登录用户/买东西等,断开链接后,从另一个地方(也是这个webapp但是是其他页面),服务端如何识别你已经有购买的东西或者判断你已登录状态;使用cookies
Cookies是服务器向客户端写入一些临时的文本文件,再次访问,从cookies中读取你的上次浏览操作状态信息,有如下规则:
1.只能写入txt文件
2.当前webapp的只能读取自己的cookie文件,不能读取别的应用的cookie
3.每个浏览器有唯一的id来区分谁操作的哪些东西
4.Cookie有生命周期,服务端写入cookie时设置,如果不进行设置,默认cookie生命
5.键值对形式保存
6.周期为瞬时的,cookie存活在内存中,当ie页面打开时就存活,关闭时就消亡
7.同一个servlet/jsp下cookies能被同一个路径或子路径里面的servlet/jsp读取,不能被其他路径的读取(路径==url)
写入cookies:
Cookie cookie = new Cookie("Cookies_name_no_life_" + i,"Cookies Vaule " +i);
resp.addCookie(cookie);
读取cookies:
Cookie[] cookies = req.getCookies();
cookies[i].getName();
cookies[i].getValue();
注意:客户端也可以阻止服务器向客户端写入cookie,在ie中设置安全选项,提高安全等级即可
测试代码:
写cookies:
package com.jack.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WriteCookies extends HttpServlet{
//写入cookie
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
for(int i =0;i<3;i++){
//无生命周期的cookie
Cookie cookie = new Cookie("Cookies_name_no_life_" + i,"Cookies Vaule " +i);
resp.addCookie(cookie);
cookie = new Cookie("Cookies_name_" + i,"Cookies Vaule " +i);
cookie.setMaxAge(60); //60秒的生命周期
resp.addCookie(cookie);
}
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.write("<HTML><HEAD>write a cookie to client</HEAD>\n"+
"<BODY BGCOLOR=\"#FDF5E6\">\n"+ "<H1 ALIGN=\"CENTER\">cookies</H1>\n"+
"<A HREF=\"ReadCookies\">\n" + "<CODE>ReadCookies</CODE>Servlet</A>"+
"</BODY></HTML>");
}
}
读取cookies:
package com.jack.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ReadCookies extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.write("<HTML><HEAD>Read a cookies</HEAD>" +
"<BODY><H1 ALIGN=\"CENTER\">READ A COOKIES</H1>\n"+
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FEF5E6\"><TH>Cookies name</TH><TH>Cookies Value</TH>\n");
Cookie[] cookies = req.getCookies();
for(int i = 0;i < cookies.length;i++){
writer.write("<TR><TD>"+cookies[i].getName() + "</TD><TD>"+cookies[i].getValue() + "</TD>\n");
}
}
}
测试结果: