Cookie (二)
一、Cookie细节
1、一个Cookie只能标识一种信息,它至少含有一个标识该信息的名称(NAME)和设置值(VALUE)。
2、一个WEB站点可以给一个WEB浏览器发送多个Cookie,一个WEB浏览器也可以存储多个WEB站点提供的Cookie。
3、浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。
4、如果创建了一个cookie,并将他发送到浏览器,默认情况下它是一个会话级别的cookie(即存储在浏览器的内存中),用户退出浏览器之后即被删除。若希望浏览器将该cookie存储在磁盘上,则需要使用maxAge,并给出一个以秒为单位的时间。将最大时效设为0则是命令浏览器删除该cookie。
5、注意,删除cookie时,path必须一致,否则不会删除
二、Cookie应用--------------显示用户上次浏览过的商品
案例:
package com.hbsi.dao;
import java.util.List;
import com.hbsi.domain.Book;
public interface BookDao {
public List<Book> getAll();
public Book getBook(String id);
}
package com.hbsi.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.hbsi.domain.Book;
import com.hbsi.util.JDBCConnection;
public class BookDaoImple implements BookDao {
public List<Book> getAll() {
Connection conn = null;
PreparedStatement pt = null;
ResultSet rs = null;
try {
conn = JDBCConnection.getConnection();
String sql = "select * from book";
pt = conn.prepareStatement(sql);
rs = pt.executeQuery();
List<Book> list = new ArrayList<Book>();
while (rs.next()) {
Book b = new Book();
b.setId(rs.getString("id"));
b.setName(rs.getString("name"));
b.setAuthor(rs.getString("author"));
b.setDescrip(rs.getString("descrip"));
list.add(b);
}
return list;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
JDBCConnection.closeDB(conn, pt, rs);
}
}
public Book getBook(String id) {
Connection conn = null;
PreparedStatement pt = null;
ResultSet rs = null;
try {
conn = JDBCConnection.getConnection();
String sql = "select * from book where id=?";
pt = conn.prepareStatement(sql);
pt.setString(1, id);
rs = pt.executeQuery();
//Book b = null;
if(rs.next()){
Book b = new Book();
b.setId(rs.getString("id"));
b.setName(rs.getString("name"));
b.setAuthor(rs.getString("author"));
b.setDescrip(rs.getString("descrip"));
return b;
}
return null;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
JDBCConnection.closeDB(conn, pt, rs);
}
}
public static void main(String [] args){
BookDao db = new BookDaoImple();
Book b = db.getBook("2");
System.out.println(b.getName());
}
}
package com.hbsi.domain;
public class Book {
private String id;
private String name;
private String author;
private String descrip;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescrip() {
return descrip;
}
public void setDescrip(String descrip) {
this.descrip = descrip;
}
}
package com.hbsi.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hbsi.dao.BookDao;
import com.hbsi.dao.BookDaoImple;
import com.hbsi.domain.Book;
public class ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//显示所有书名
out.print("本网站的商品有:<br/>");
BookDao bd = new BookDaoImple();
List<Book> list = bd.getAll();
for(Book book:list){
//System.out.println(book.getId());
//out.print("<a href='/BookHistory/servlet/CookieDemo2'?id="+book.getId()+">"+book.getName()+"</a><br/>");
out.print("<a href='/BookHistory/servlet/ServletDemo2?id="+book.getId()+"' target='_blank'>"+book.getName()+"</a><br/>");
}
//显示浏览过的书名 bookhistory=1,2,3
out.print("你浏览过的商品:<br/>");
Cookie[] cookies = request.getCookies();
for(int i=0;cookies!=null && i<cookies.length;i++){
if(cookies[i].getName().equals("bookhistory")){
String[] ids = cookies[i].getValue().split(",");
for(String id:ids){
Book book = bd.getBook(id);
out.print(book.getName()+"<br/>");
}
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package com.hbsi.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hbsi.dao.BookDao;
import com.hbsi.dao.BookDaoImple;
import com.hbsi.domain.Book;
public class ServletDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//显示书的详细信息,根据id获取
String id = request.getParameter("id");
System.out.println(id);
BookDao bd = new BookDaoImple();
Book book = bd.getBook(id);
System.out.println(book);
out.print("书号:"+book.getId()+"<br/>");
out.print("书名:"+book.getName()+"<br/>");
out.print("作者:"+book.getAuthor()+"<br/>");
out.print("描述:"+book.getDescrip()+"<br/>");
//将书号写入cookie
//bookhistory=null 1 1
//bookhistory=2,3,1 1 1,2,3
//bookhistory=2,3,5 1 1,2,3
//bookhistory=2,3 1 1,2,3
String cookieValue = buildCookValue(id,request);
Cookie cookie = new Cookie("bookhistory",cookieValue);
cookie.setMaxAge(30*24*3600);
cookie.setPath("/BookHistory");
response.addCookie(cookie);
}
public String buildCookValue(String id,HttpServletRequest request){
String bookhistory=null;
Cookie[] cookies = request.getCookies();
for(int i=0;cookies!=null && i<cookies.length;i++){
if(cookies[i].getName().equals("bookhistory")){
bookhistory = cookies[i].getValue();
}
}
if(bookhistory == null){
return id;
}
LinkedList<String> list = new LinkedList(Arrays.asList(bookhistory.split(",")));
if(list.contains(id)){
list.remove(id);
list.addFirst(id);
}else{
//bookhistory=2,3,5 1 1,2,3
//bookhistory=2,3 1 1,2,3
if(list.size()>=3){
list.removeLast();
list.addFirst(id);
}else{
list.addFirst(id);
}
}
StringBuffer sb = new StringBuffer();
for(String bid: list){
sb.append(bid+",");
}
return sb.deleteCharAt(sb.length()-1).toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package com.hbsi.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCConnection {
/**
* @param args
*/
static String driver;
static String url;
static String user;
static String password;
static{
//通过类名调动类的加载器获取源的流,InputString是输入流,连接到db.properties的文件中
InputStream in=JDBCConnection.class.getClassLoader().getResourceAsStream("db.properties");
//产生Properties对象,在until包中,代表一个持久的属性集
Properties pr=new Properties();
try {
//load作用:从输入流中读取属性列表
pr.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//通过getProperty方法传一个key进去,key对应db.properties中定义的
driver=pr.getProperty("driver");
url=pr.getProperty("url");
user=pr.getProperty("user");
password=pr.getProperty("password");
}
public static Connection getConnection(){
Connection con=null;
try {
Class.forName(driver);}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
con=DriverManager.getConnection(url, user, password);
//System.out.println("成功!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public static void closeDB(Connection con,Statement st,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void dbClose1(Connection con,Statement st){
if(st!=null)
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(con!=null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
getConnection();
}
}
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/java
user=root
password=root