怎么同步两个不同域之间的Cookie值

怎么同步两个不同域之间的Cookie值

我想利用多线程在DetailServlet中利用post方法发送HttpPost httpPost = new HttpPost(server + "/" + method + "?cookies=" + cookies);

http://img1.sycdn.imooc.com//climg/5a8ee32e0001139608660171.jpg

BrowseServlet中设置拦截/browse/setCookie.do但是发现BrowseServlet中接收不到,怎么解决这个问题呢?

Cookie在detail.jsp中的显示

http://img1.sycdn.imooc.com//climg/5a8ee3810001db7013050112.jpg

在browse_list.jsp中的显示

http://img1.sycdn.imooc.com//climg/5a8ee3a400019c1210960153.jpg

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!--欢迎页面-->
    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>
    <!--过滤器-->
    <filter>
        <filter-name>CharsetFilter</filter-name>
        <filter-class>filter.CharsetFilter</filter-class>
        <init-param>
            <param-name>charset</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharsetFilter</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>
    
    <servlet>
        <servlet-name>ProductServlet</servlet-name>
        <servlet-class>servlet.ProductServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ProductServlet</servlet-name>
        <url-pattern>/product/list.do</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>CartServlet</servlet-name>
        <servlet-class>servlet.CartServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CartServlet</servlet-name>
        <url-pattern>/cart/cart.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>CartServlet</servlet-name>
        <url-pattern>/cart/decr.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>CartServlet</servlet-name>
        <url-pattern>/cart/incr.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>CartServlet</servlet-name>
        <url-pattern>/cart/delete.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>CartServlet</servlet-name>
        <url-pattern>/cart/list.do</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>FavoriteServlet</servlet-name>
        <servlet-class>servlet.FavoriteServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FavoriteServlet</servlet-name>
        <url-pattern>/favorite/favorite.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>FavoriteServlet</servlet-name>
        <url-pattern>/favorite/delete.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>FavoriteServlet</servlet-name>
        <url-pattern>/favorite/list.do</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>DetailServlet</servlet-name>
        <servlet-class>servlet.DetailServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DetailServlet</servlet-name>
        <url-pattern>/detail/detail.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>DetailServlet</servlet-name>
        <url-pattern>/detail/removeCookie.do</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>BrowseServlet</servlet-name>
        <servlet-class>servlet.BrowseServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>BrowseServlet</servlet-name>
        <url-pattern>/browse/list.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>BrowseServlet</servlet-name>
        <url-pattern>/browse/delete.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>BrowseServlet</servlet-name>
        <url-pattern>/browse/setCookie.do</url-pattern>
    </servlet-mapping>


    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/views/error/404.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/views/error/500.jsp</location>
    </error-page>
</web-app>

DetailServlet

public class DetailServlet extends HttpServlet {
    //创建java线程池对象,创建10个线程池
    private ExecutorService service = Executors.newFixedThreadPool(10);

    //实现同步cookie的方法
    private void syncCookie(String server, String method, String cookies) {
        //调用提交的方法
        service.submit(new Runnable() {
            @Override
            public void run() {
                //post请求调用
                HttpPost httpPost = new HttpPost(server + "/" + method + "?cookies=" + cookies);
                CloseableHttpClient httpClient = null;
                CloseableHttpResponse response = null;
                try {
                    httpClient = HttpClients.createDefault();
                    response = httpClient.execute(httpPost);
                    HttpEntity entity = response.getEntity();
                    String responseContent = EntityUtils.toString(entity, "utf-8");
                    System.out.println("==============" + responseContent);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (null != response) {
                        try {
                            response.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (null != httpClient) {
                        try {
                            httpClient.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (Objects.equals("/detail/detail.do", req.getServletPath())) {
            //为list界面传来请求
            String productId = req.getParameter("productId");
            if (null != productId && !"".equals(productId)) {
                //声明一个existCookie
                Cookie existCookie = null;
                //遍历系统存在的cookie
                //从cookie中取出所有数据
                for (Cookie cookie : req.getCookies()) {
                        if (Objects.equals("productIds", cookie.getName())) {
                            //当cookie与产品id匹配时
                            existCookie = cookie;
                            break;
                        }
                }
                //当existCookie为空时
                if (null == existCookie) {
                    //新建一个cookie
                    existCookie = new Cookie("productIds", productId);
                    //调用同步coookie的方法
                    syncCookie("/browse", "setCookie.do", productId);
                } else {
                    //把productIds中的productId提取出来
                    String[] productIds = existCookie.getValue().split("%2C");
                    if (!"".equals(productIds)) {
                        /**
                         * 当productIds不为""字符串时
                         * 定义一个boolean控制是否添加新的cookie
                         */
                        StringBuilder stringBuilder = new StringBuilder();
                        Boolean addCookieFlag = false;
                        //遍历数组
                        for (String cookieId : productIds) {
                            //当cookie存在于原有cookies时,为真
                            Boolean cookieFlag = false;
                            if (cookieId.equals(productId)) {
                                //当productId与原有id匹配
                                cookieFlag = true;
                            }
                            //反馈addCookieFlag是否添加新的cookie
                            addCookieFlag = cookieFlag || addCookieFlag;
                        }
                        //根据addCookieFlag来决定是否添加新cookie
                        if (addCookieFlag) {
                            //存在即设置为原有cookie
                            existCookie.setValue(existCookie.getValue());
                            //调用同步cookie的方法
                            syncCookie("/browse", "setCookie.do", existCookie.getValue());
                        } else {
                            //不存在添加新cookie
                            for (String cookieId : productIds) {
                                //把原有id添加到stringBuilder
                                stringBuilder.append(cookieId + "%2C");
                            }
                            //添加新的cookie
                            stringBuilder.append(productId + "%2C");
                            //为cookie设置新的值
                            existCookie.setValue(stringBuilder.toString());
                            //调用同步cookie的方法
                            syncCookie("/browse", "setCookie.do", stringBuilder.toString());
                        }
                    }
                }
                //把cookie添加到当前服务器
                resp.addCookie(existCookie);
                //把id匹配到的产品放到request中
                req.setAttribute("product", ProduceService.getProduct(Long.valueOf(productId)));
                //转发回详情页面
                req.getRequestDispatcher("/WEB-INF/views/biz/detail.jsp").forward(req, resp);
            }
        } else if (Objects.equals("/detail/removeCookie.do", req.getServletPath())) {
            //接收cookie的值
            String cookies = req.getParameter("cookies");
            //把cookie写入response作用域中
            resp.addCookie(new Cookie("productIds", cookies));
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/text;charset=utf-8");
            //写入输出流
            PrintWriter out = null;
            try {
                out = resp.getWriter();
                out.write("ok");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != out) {
                    out.close();
                }
            }
        }
    }
}

BrowseServlet

public class BrowseServlet extends HttpServlet {
    //创建java线程池对象,创建10个线程池
    private ExecutorService service = Executors.newFixedThreadPool(10);

    //实现同步cookie的方法
    private void syncCookie(String server, String method, String cookies) {
        //调用提交的方法
        service.submit(new Runnable() {
            @Override
            public void run() {
                //post请求调用
                HttpPost httpPost = new HttpPost(server + "/" + method + "?cookies=" + cookies);
                CloseableHttpClient httpClient = null;
                CloseableHttpResponse response = null;
                try {
                    httpClient = HttpClients.createDefault();
                    response = httpClient.execute(httpPost);
                    HttpEntity entity = response.getEntity();
                    String responseContent = EntityUtils.toString(entity, "utf-8");
                    System.out.println("==============" + responseContent);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (null != response) {
                        try {
                            response.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (null != httpClient) {
                        try {
                            httpClient.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (Objects.equals("/browse/list.do", req.getServletPath())) {
            String cookieProducts = null;
            List<Product> productList = new ArrayList<>();
            //从cookie中取出所有数据
            for (Cookie cookie : req.getCookies()) {
                if (Objects.equals("productIds", cookie.getName())) {
                    //把产品id提取出来
                    cookieProducts = cookie.getValue();
                    break;
                }
            }
            if (null != cookieProducts && !"".equals(cookieProducts)) {
                //把cookieProducts中的productId提取出来
                String[] productIds = cookieProducts.split("%2C");
                for (String productId : productIds) {
                    //调用得到商品的方法
                    productList.add(ProduceService.getProduct(Long.valueOf(productId)));
                }
            }
            //把productList放进request中
            req.setAttribute("products", productList);
            //转发回浏览记录页面
            req.getRequestDispatcher("/WEB-INF/views/biz/browse_list.jsp").forward(req, resp);
        } else if (Objects.equals("/browse/delete.do", req.getServletPath())) {
            //为删除浏览记录商品请求
            String productId = req.getParameter("productId");
            if (null != productId && !"".equals(productId)) {
                //从cookie中取出所有数据
                for (Cookie cookie : req.getCookies()) {
                    if (Objects.equals("productIds", cookie.getName())) {
                        //把productIds中的productId提取出来
                        String[] productIds = cookie.getValue().split("%2C");
                        StringBuilder stringBuilder = new StringBuilder();
                        for (String cookieId : productIds) {
                            if (cookieId.equals(productId)) {
                                continue;
                            }
                            //把剩下的id要回来
                            stringBuilder.append(cookieId + "%2C");
                        }
                        //为cookie设置新的值
                        cookie.setValue(stringBuilder.toString());
                        //调用同步cookie的方法
                        syncCookie("/detail","removeCookie.do",stringBuilder.toString());
                        resp.addCookie(cookie);
                    }
                }
                //重定向
                resp.sendRedirect("/browse/list.do");
            }
        } else if (Objects.equals("/browse/setCookie.do", req.getServletPath())) {
            //为其它应用传来的setCookie请求
            String cookies = req.getParameter("cookies");
            //把cookie写入response作用域中
            resp.addCookie(new Cookie("productIds", cookies));
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/text;charset=utf-8");
            //写入输出流
            PrintWriter out = null;
            try {
                out = resp.getWriter();
                out.write("ok");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != out) {
                    out.close();
                }
            }
        }
    }
}


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

2回答
好帮手慕珊 2018-02-25 13:30:13

syncCookie("/browse", "setCookie.do", productId);第一个参数不应该是/browse,第一个参数是server,也就是类似于http://localhost:8080这种形式,后面接/browse/setCookie.do?  ,所以第二个参数应该是/browse/setCookie.do,所以组合起来应该是一个完整的url,看看你的server应该是什么,改完之后再试试.

祝学习愉快!

  • 提问者 湛蓝牛仔 #1
    server用的是默认的http://localhost:8080/但是组成了http://localhost:8080/browse/setCookie.do?cookies=...的完整url,BrowseServlet也还是拦截不到/browse/setCookie.do
    2018-02-25 14:09:00
  • 一叶知秋519 回复 提问者 湛蓝牛仔 #2
    如果直接使用http://localhost:8080/browse/setCookie.do这个完整路径来访问,可以进入/browse/setCookie.do这段代码吗?
    2018-02-26 10:50:50
  • 提问者 湛蓝牛仔 回复 一叶知秋519 #3
    也还是访问不到,我交最后一个作业的时候,可不可以把这个项目也一起提交,单独提这个问题?
    2018-02-26 11:38:01
慕粉0907203 2018-02-24 22:47:13

我觉得你把browse_list.jsp中的代码一块粘贴出来,还有就是你可以自己走断点跟踪一下呀。

  • 提问者 湛蓝牛仔 #1
    detail.jsp和browse_list.jsp用的是老师的代码,没修改,所以没有贴出来;还有就是走断点,BrowseServlet拦截不到/browse/setCookie.do,断点都没有跳转到BrowseServlet就运行完了,所以我想问问为什么拦截不到?我在web.xml已经注册了<servlet-mapping> <servlet-name>BrowseServlet</servlet-name> <url-pattern>/browse/setCookie.do</url-pattern> </servlet-mapping>
    2018-02-24 23:05:58
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
从网页搭建入门Java Web2018版
  • 参与学习           人
  • 提交作业       1088    份
  • 解答问题       10205    个

如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!

了解课程
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师