Java_常瑞鹏 深入Cookie

java

Cookie API

javax.servlet.http.Cookie类用于创建一个Cookie,response接口也中定义了一个addCookie方法,它用于在其响应头中增加一个相应的Set-Cookie头字段。同样,request接口中也定义了一个getCookies方法,它用于获取客户端提交的Cookie。Cookie类的方法:

public Cookie(String name,String value)

setValue与getValue方法

setMaxAge与getMaxAge方法

setPath与getPath方法

setDomain与getDomain方法

getName方法

Set-Cookie:username=qiujy;Domain=localhost;path=/

Cookie:username=qiujy;$Path=/jsp_04_servlet

Cookie细节

一个Cookie只能标识一种信息,它至少含有一个标识该信息的名称(NAME)和设置值(VALUE)。

一个WEB站点可以给一个WEB浏览器发送多个Cookie,一个WEB浏览器也可以存储多个WEB站点提供的Cookie。

浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。

如果创建了一个cookie,并将他发送到浏览器,默认情况下它是一个会话级别的cookie(即存储在浏览器的内存中),用户退出浏览器之后即被删除。若希望浏览器将该cookie存储在磁盘上,则需要使用maxAge,并给出一个以秒为单位的时间。将最大时效设为0则是命令浏览器删除该cookie。

注意,删除cookie时,path必须一致,否则不会删除

Cookie应用

显示用户上次浏览过的商品

package com.hbsi.domain;

public class Book {

private String id;

private String name;

private String author;

private String descript;

public String getId() {

return id;

}

public void setId(String string) {

this.id = string;

}

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 getDescript() {

return descript;

}

public void setDescript(String descript) {

this.descript = descript;

}


}

------------------------------------------------------------------------------------------------

package com.hbsi.dao;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import com.hbsi.domain.Book;

import com.hbsi.util.DBManager;

public class BookDao {

public List<Book> getAll(){

Connection conn=null;

PreparedStatement pt=null;

ResultSet rs =null;

try {

conn=DBManager.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.setDescript(rs.getString("descript"));

list.add(b);

}

return list;

} catch (SQLException e) {

throw new RuntimeException(e);

}finally{

DBManager.closeDB(conn, pt, rs);

}

}

public Book getBook(String id){

Connection conn=null;

PreparedStatement pt=null;

ResultSet rs =null;

try {

conn=DBManager.getConnection();

String sql="select * from book where id=?";

pt=conn.prepareStatement(sql);

pt.setString(1, id);

rs=pt.executeQuery();

if(rs.next()){

Book b=new Book();

b.setId(rs.getString("id"));

b.setName(rs.getString("name"));

b.setAuthor(rs.getString("author"));

b.setDescript(rs.getString("descript"));

return b;

}

return null;

} catch (SQLException e) {

throw new RuntimeException(e);

}finally{

DBManager.closeDB(conn, pt, rs);

}

}

public static void main(String [] args){

BookDao db = new BookDao();

Book b = db.getBook("2");

System.out.println(b.getName());

}

}

--------------------------------------------------------------------------------------------

package com.hbsi.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

importjavax.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.domain.Book;

public class CookieDemo1 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 BookDao();

List<Book> list=bd.getAll();

for(Book book:list){

out.print("<a href='/BookHistory/servlet/CookieDemo2?);

}

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.Iterator;

import java.util.LinkedList;

importjavax.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.domain.Book;

public class CookieDemo2 extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");

PrintWriter out=response.getWriter();

String id =request.getParameter("id");

System.out.println(id);

BookDao bd=new BookDao();

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.getDescript()+"<br/>");

String cookieValue=buildCookValue(id,request);

Cookie cookie =new Cookie("bookhistory",cookieValue);

cookie.setMaxAge(30*24*3600);

cookie.setPath("/BookHistory");

response.addCookie(cookie);

}


private 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{

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);

}

}

以上是 Java_常瑞鹏 深入Cookie 的全部内容, 来源链接: utcz.com/z/393263.html

回到顶部