package pm_cn.itcast.cookie; |
import java.io.IOException; |
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 pm_cn.itcast.utils.CookieUtils; |
public class ShowHistoryServlet extends HttpServlet { |
public void doGet(HttpServletRequest request, HttpServletResponse response) |
throws ServletException, IOException { |
|
// 获得 当前查看的商品的 id |
|
String id = request.getParameter( "id" ); |
|
// 获得 带过来的 cookie, 然后 查找 出 目标 cookie |
Cookie[] cookies = request.getCookies(); |
|
Cookie historyCookie = CookieUtils.findTargetCookie(cookies, "history" ); |
|
// 如果 cookie 为空 ,则说明之前没有浏览过 |
|
if (historyCookie== null ){ |
|
// 就写一个 history cookie 回去 |
Cookie cookie = new Cookie( "history" , id); |
// 持久化 cookie |
cookie.setMaxAge( 60 * 60 * 24 * 7 ); |
cookie.setPath( "/" ); |
|
response.addCookie(cookie); |
} else { |
//如果 不为空, 说明 浏览过 |
|
// 获得 之前 浏览过的 值 |
String value = historyCookie.getValue(); // 1,3,4 |
|
String[] records = value.split( "," ); |
|
if (!checkExistId(records,id)){ |
|
// 如果 进来 ,则 说明之前没 有 浏览过 , 就要将其 添加到 value中 ,拼接后 写回去 . |
// 构建 一个新的 cookie , 然后 设置 value 为 原来的 值 在 加上 id |
Cookie newCookie = new Cookie( "history" ,value+ "," + id); |
newCookie.setMaxAge( 60 * 60 * 24 * 7 ); |
newCookie.setPath( "/" ); |
response.addCookie(newCookie); |
} |
} |
|
response.setContentType( "text/html;charset=utf-8" ); |
response.getWriter().print( "哥们, 你 浏览商品 成功 ... <a href='/day12/cookie/products.jsp'>返回</a>" ); |
|
} |
private boolean checkExistId(String[] records, String id) { |
|
for (String record : records) { |
|
if (record.equals(id)){ |
// 说明 有 就 return true |
return true ; |
} |
} |
|
return false ; |
} |
public void doPost(HttpServletRequest request, HttpServletResponse response) |
throws ServletException, IOException { |
doGet(request, response); |
} |
} |