您的位置:首页 > 其它

利用Cookie记录用户浏览的图片

2016-07-26 01:23 465 查看
一:当用户点击图片时,记录用户的浏览信息

       public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");
String imgpath=request.getParameter("img");//浏览图片的信息
Cookie cs[]=request.getCookies();//获取可访问cookie
boolean flag=false;
if(cs!=null){
for(Cookie c:cs){
if(!c.getName().equals("imgs"))//获取记录图片信息的cookie
continue;
String split="jrd_splitImg###";//分隔符
String imgsPath=c.getValue();
String[] strs=imgsPath.split(split);
imgsPath=imgpath;//将图片的显示位置置前
boolean boo=false;
for(String str:strs){
if(str.equals(imgpath))
boo=true;//当图片再次被浏览时
}
if(boo){
for(String str:strs){
if(str.equals(imgpath))//去除重复信息
continue;
imgsPath=imgsPath+split+str;
}
}else{//否则直接添加
int count=1;
for(String str:strs){
if(count>=3)//限制记录的个数
break;
imgsPath=imgsPath+split+str;
count++;
}
}
c.setValue(imgsPath);
c.setPath(request.getContextPath());//必须设置的path路径与请求的cookie的path一致,否则为不同对象
c.setMaxAge(60*60);
response.addCookie(c);
flag=true;
}
}
if(flag==false){//第一次访问时,创建cookie对象
Cookie cookie=new Cookie("imgs", imgpath);
cookie.setPath(request.getContextPath());//path设置要可访问,且可被显示的JSP访问
cookie.setMaxAge(60*60);//设置有效时间,以秒为单位
response.addCookie(cookie);//发送cookie
}

PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.println("<img src='"+imgpath+"'/>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}jsp界面显示:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<style type="text/css">
img{
width: 200px;
height: 200px;
}
.last{
width: 40px;
height: 40px;
}

</style>

</head>

<body>
<h1>最近访问的图片</h1>
<%
Cookie[] cs=request.getCookies();
for(Cookie c:cs){
if(!c.getName().equals("imgs"))//获取图片信息
continue;
String split="jrd_splitImg###";
String imgsPath=c.getValue();
String[] strs=imgsPath.split(split);
for(String str:strs){
%>
<img class="last" src="<%=str%>"/>
<%}} %>
<hr/>
<%
for(int i=1;i<=8;i++){
String path=request.getContextPath()+"/imgs/"+i+".jpg";
%>
<a href="showServlet?img=<%=path %>">
<img src="<%=path%>"/></a>
<%} %>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Tag cookie