Session,Cookie


案例一:利用Cookie显示用户上次访问时间

 1 //解决中文乱码问题
2 response.setCharacterEncoding("UTF-8");
3 response.setHeader("content-type","text/html;charset=UTF-8");
4 PrintWriter writer = response.getWriter();
5 writer..write("您上次的访问时间是:<br/>")
6
7 //1.检查一下有没有Cookie,如果没有,则不显示,如果有则显示
8 Cookie[] cookie = request.getCookies();
9 for(int i=0;i<cookie.length;i++)
10 {
11 if(cookie[i].getName().equals("LastAccessTime"))
12 {
13 String time = cookie[i].getValue();//some question
14 writer.write("您上次的访问时间是:"+time+"<br/>");
15 }
16 }
17
18 //2.向浏览器发送本次访问时间的Cookie
19 Date currentDate = new Date(System.currentTimeMillis());
20 Cookie currentCookie = new Cookie("LastAccessTime",currentDate.toLocaleString());
21 currentCookie.setMaxAge(1*30*24*60*60);
22 currentCookie.setPath("/Thursday/");
23 response.addCookie(currentCookie);
24 //删除Cookie采用发送一个新的Cookie覆盖想要删除的Cookie的方式,路径必须一致,设置新的Cookie的过期时间为0

案例二:利用Cookie显示商品的浏览记录

 1 //显示商品
2 response.setCharacterEncoding("UTF-8");
3 response.setHeader("content-type", "text/html;charset=UTF-8");
4
5 PrintWriter writer = response.getWriter();
6 writer.write("<a href='/Thursday/servlet/ServletDemo3?ID=1'>"+DB.getAll().get(1).getProductName()+"</a><br/>");
7 writer.write("<a href='/Thursday/servlet/ServletDemo3?ID=2'>"+DB.getAll().get(2).getProductName()+"</a><br/>");
8 writer.write("<a href='/Thursday/servlet/ServletDemo3?ID=3'>"+DB.getAll().get(3).getProductName()+"</a><br/>");
9 writer.write("<a href='/Thursday/servlet/ServletDemo3?ID=4'>"+DB.getAll().get(4).getProductName()+"</a><br/>");
10
11 //显示浏览过的商品
12 Cookie[] cookie = request.getCookies();
13 for(int i=0;cookie!=null&&i<cookie.length;i++)
14 {
15 if(cookie[i].getName().equals("browseredProduct"))
16 {
17 writer.write("您已经浏览过的商品<br/>");
18 String[] IDs = cookie[i].getValue().split("\\,");//1,2,3
19 for(String ID : IDs)
20 {
21 writer.write(DB.getAll().get(Integer.parseInt(ID)).getProductName()+"<br/>");
22 }
23 }
24 }

 

 1 response.setCharacterEncoding("UTF-8");
2 response.setHeader("content-type", "text/html;charset=UTF-8");
3
4 //显示详细信息
5 int ID = Integer.parseInt(request.getParameter("ID"));
6 PrintWriter writer = response.getWriter();
7 writer.write(DB.getAll().get(ID).getProductName()+"<br/>");
8 writer.write(DB.getAll().get(ID).getProductPrice()+"<br/>");
9 writer.write(DB.getAll().get(ID).getProductDesc()+"<br/>");
10
11 //回发Cookie给浏览器
12 String value = setCookieValue(ID,request);
13 Cookie cookie = new Cookie("browseredProduct",value);
14 cookie.setMaxAge(1*30*24*60*60);
15 cookie.setPath("/Thursday/");
16 response.addCookie(cookie);

 

 

案例三:利用Session实现简单的购物

 

 1 /*
2 *新建选项卡,点击也面超链弹出新窗口,他们共用Session,打开新的浏览器,则创建新的Session(IE8除外)
3 */
4 //显示商品页面
5 response.setCharacterEncoding("UTF-8");
6 response.setHeader("content-type", "text/html;charset=UTF-8");
7 //解决禁用Cookie的情况
8 HttpSession session = request.getSession();
9
10 //解决关闭浏览器,购买记录消失的情况
11 Cookie cookie = new Cookie("JSESSIONID",session.getId());
12 cookie.setMaxAge(30*60);
13 cookie.setPath(request.getContextPath());
14 response.addCookie(cookie);
15
16 String url1 = response.encodeURL("/Thursday/servlet/ServletDemo5?ID=1");
17 String url2 = response.encodeURL("/Thursday/servlet/ServletDemo5?ID=2");
18 String url3 = response.encodeURL("/Thursday/servlet/ServletDemo5?ID=3");
19 String url4 = response.encodeURL("/Thursday/servlet/ServletDemo5?ID=4");
20 PrintWriter writer = response.getWriter();
21 writer.write("<a href='"+url1+"'>"+DB.getAll().get(1).getProductName()+"</a><br/>");
22 writer.write("<a href='"+url2+"'>"+DB.getAll().get(2).getProductName()+"</a><br/>");
23 writer.write("<a href='"+url3+"'>"+DB.getAll().get(3).getProductName()+"</a><br/>");
24 writer.write("<a href='"+url4+"'>"+DB.getAll().get(4).getProductName()+"</a><br/>");

 

 1 //商品购买页面
2 response.setCharacterEncoding("UTF-8");
3 response.setHeader("content-type", "text/html;charset=UTF-8");
4
5 String ID = request.getParameter("ID");
6 HttpSession session = request.getSession();
7
8 List<String> list = (List<String>)session.getAttribute("PurcharsedPro");
9
10 if(list==null)
11 {
12 list = new ArrayList<String>();
13 session.setAttribute("PurcharsedPro", list);
14 }
15 list.add(ID);
16
17 String url = response.encodeRedirectURL(request.getContextPath()+"/servlet/ServletDemo6");
18 response.sendRedirect(url);//request.getContextPath()代表/Thursday
19 return;

 

 1 //结账页面
2 response.setCharacterEncoding("UTF-8");
3 response.setHeader("content-type", "text/html;charset=UTF-8");
4
5 PrintWriter writer = response.getWriter();
6 writer.write("您已购买:<br/>");
7
8 HttpSession session = request.getSession(false);
9 List<String> list = (List<String>) session.getAttribute("PurcharsedPro");
10
11 for(String str : list)
12 {
13 writer.write(DB.getAll().get(Integer.parseInt(str)).getProductName()+"<br/>");
14 }

 

 

案例四:利用Session实现服务器端防止表单重复提交

 

 1 /*
2 *思路:首先输出表单的时候,生成一个令牌给表单,并在服务器端也存储备份,处理表单请求的时候,查看令牌是否有效决定是否处理请求,最后删除服务器端的令牌
3 */
4 //输出表单页面
5 String ran = TokenProcessor.getInstance().generateRandom();
6 request.getSession().setAttribute("token", ran);
7 request.getRequestDispatcher("/index.jsp").forward(request, response);
8 //随机数发生器,设置成单例模式,可以减小随机数重复的概率
9 class TokenProcessor
10 {
11 private TokenProcessor(){}
12 private static final TokenProcessor instance = new TokenProcessor();
13 public static TokenProcessor getInstance()
14 {
15 return instance;
16 }
17 public String generateRandom()
18 {
19 Random ran = new Random();
20 String randomNum = System.currentTimeMillis()+ran.nextInt()+"";//由于产生的随机数长度不定,所以randommNum长度也不一定,为了实现定长,采取获取数据摘要来实现定长
21 try
22 {
23 MessageDigest md = MessageDigest.getInstance("md5");
24 byte[] str = md.digest(randomNum.getBytes());//由于str可能是任意的数,为防止出现查不到码表的问题,所以必须采用base64编码方式进行编码
25 BASE64Encoder encoder = new BASE64Encoder();
26 randomNum = encoder.encode(str);
27 }
28 catch (NoSuchAlgorithmException e)
29 {
30 e.printStackTrace();
31 }
32 return randomNum;
33 }
34 }

 

1 //显示表单的JSP页面
2 <form action="/Thursday/servlet/DoPost" method="post">
3 姓名:<input type="text" name="userName">
4 <input id="registerButton" type="submit" value="注册">
5 <input type="hidden" name="token" value="${token }">
6 </form>

 

 1 //处理表单请求的页面
2 boolean b = isValid(request);
3 if(!b)
4 {
5 System.out.println("重复提交");
6 }
7 else
8 {
9 System.out.println("合法提交");
10 }
11 private boolean isValid(HttpServletRequest request)
12 {
13 String clientRandom = request.getParameter("token");
14 String serveRandom = (String) request.getSession().getAttribute("token");
15 if(clientRandom==null)
16 {
17 return false;
18 }
19
20 if(serveRandom==null)
21 {
22 return false;
23 }
24
25 if(!clientRandom.equals(serveRandom))
26 {
27 return false;
28 }
29
30 request.getSession().removeAttribute("token");
31 return true;
32 }






 

posted @ 2011-12-23 12:31  xiao秋  阅读(1124)  评论(0编辑  收藏  举报