怎么同步两个不同域之间的Cookie值
我想利用多线程在DetailServlet中利用post方法发送HttpPost httpPost = new HttpPost(server + "/" + method + "?cookies=" + cookies);
到BrowseServlet中设置拦截/browse/setCookie.do但是发现BrowseServlet中接收不到,怎么解决这个问题呢?
Cookie在detail.jsp中的显示
在browse_list.jsp中的显示
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(); } } } } }
119
收起
正在回答 回答被采纳积分+1
2回答
从网页搭建入门Java Web2018版
- 参与学习 人
- 提交作业 1088 份
- 解答问题 10205 个
如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星