用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

显示商品浏览记录的 servlet, 主要用于维护记录,

2014-08-05 作者: jun举报

[java]代码库

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


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...