关于Cookie报错An invalid character [44] was present in the Cookie value

存入cookie的时候竟然报这个错误。。

查资料:其实很简单,你看报错信息An invalid character [44] was present in the Cookie value,ascii为44的字符是“,”,说明cookie不支持“,”,你可以换成“#”,可能与toncat版本有关,但是为了这个去换tomcat有点得不偿失

顺便记录一下利用cookie做浏览历史的demo

点击商品的时候同时获取他的pid,然后存起来

//浏览历史记录储存
		String cookieValue = buildCookie(pid, request);//产生想要的cookie中的值
		Cookie cookie = new Cookie("historyCookie", cookieValue);
		cookie.setMaxAge(1*24*3600);
		response.addCookie(cookie);
private String buildCookie(String pid, HttpServletRequest request) {
		
		String historyCookie = null;
		
		//得到请求中带来的cookie值
		Cookie[] cookies = request.getCookies();
		for (int i = 0; cookies != null && i < cookies.length; i++){
			if (cookies[i].getName().equals("historyCookie") ){
				historyCookie = cookies[i].getValue();
			}
		}
		
		//如果为空返回当前商品的id
		if (historyCookie == null){
			return pid;
		}
		
		LinkedList<String> list = new LinkedList<String>(Arrays.asList((historyCookie.split("\\-"))));
		
		//对不同的情况进行分析返回id的值
		if (list.contains(pid)){
			list.remove(pid);
		}else{
			if (list.size() >= 7){
				list.removeLast();
			}
		}
		list.addFirst(pid);
		
		StringBuffer sb = new StringBuffer();
		for (String sid : list){
			sb.append(sid + "-");
		}
		sb.deleteCharAt(sb.length()-1);
		
		return sb.toString();
	}

显示的时候:


		Cookie[] cookies = request.getCookies();
		List<Product> historyPdList = new ArrayList<>();
		for (int i = 0; cookies != null && i < cookies.length; i++){
			
			//找到我们想要的cookie
			if (cookies[i].getName().equals("historyCookie")){
				String[] pids = cookies[i].getValue().split("\\-");
				
				//得到cookie中存在的id,展现浏览过的商品
				for (String pid : pids){
					historyPdList.add(productService.findProductByPid(pid));
				}
			}
		}
		request.setAttribute("historyPdList", historyPdList);

jsp:

<c:forEach items="${historyPdList}" var="hplist">
				<a href="${pageContext.request.contextPath}/ProductServlet?method=findProductByPid&pid=${hplist.pid}">
					<li style="width: 150px;height: 216;float: left;margin: 0 8px 0 0;padding: 0 18px 15px;text-align: center;"><img src="${pageContext.request.contextPath}/${hplist.pimage}"  width="130px" height="130px" />${hplist.pname}</li>
				</a>
				</c:forEach>

猜你喜欢

转载自blog.csdn.net/BinGuoLA/article/details/81319222
今日推荐