黑马程序员技术交流社区
标题:
//显示商品的详细信息 //向客户端发送cookie
[打印本页]
作者:
tfy
时间:
2012-12-25 00:54
标题:
//显示商品的详细信息 //向客户端发送cookie
package com.itheima.cookie.app3;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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;
//显示商品的详细信息
//向客户端发送cookie
public class ShowDetailServlet 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");
Book book=BookDB.findBookById(id);
out.write("详细内容如下:<br/>");
out.write(book.toString());
//向客户端发送cookie:bookHistory=
String value=makeId(request,id);
Cookie cookie=new Cookie("bookHistory", value);
cookie.setMaxAge(Integer.MAX_VALUE);
cookie.setPath(request.getContextPath());
response.addCookie(cookie);
}
//组织id
/* 当前访问数的id 浏览器带过来的id 组织后的id
* 1 cookie 一个都没有 1
* 1 cookie有, 但不是bookHistory 1
* 1 bookHistory= 2-1 1-2
* 1 bookHistory = 3-2 1-3-2
* 1 bookHistory = 2-1-3 1-2-3
* 1 bookHistory = 2-3-4 1-2-3
*
*/
private String makeId(HttpServletRequest request, String id) {
Cookie []cs=request.getCookies();
//* 1 cookie 一个都没有 1
if(cs==null){
return id;
}
// 1 cookie有, 但不是bookHistory 1
Cookie bookHistoryCookie=null;
for(Cookie c:cs){
if("bookHistory".equals(c.getName())){
bookHistoryCookie=c;
}
}
if(bookHistoryCookie==null){
return id;
}
// * 1 bookHistory= 2-1 1-2
// * 1 bookHistory = 3-2 1-3-2
// * 1 bookHistory = 2-1-3 1-2-3
// * 1 bookHistory = 2-3-4 1-2-3
String oldIds[]=bookHistoryCookie.getValue().split("\\-");
LinkedList<String> list=new LinkedList<String>(Arrays.asList(oldIds));
if(list.size()<3){
if(list.contains(id)){// * 1 bookHistory= 2-1 1-2
list.remove(id);
}
list.addFirst(id);
}else{
if(list.contains(id)){// 1 bookHistory = 3-2 1-3-2
list.remove(id);
}else{
list.removeLast();
}
list.addFirst(id);
}
// 1 2 3 1-2-3
StringBuffer sb=new StringBuffer();
for(int i=0;i<list.size();i++){
if(i>0){
sb.append("-");
}
sb.append(list.get(i));
}
return sb.toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
作者:
济南王昭珽
时间:
2012-12-25 10:38
{:soso_e179:}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2