JavaWeb----Cookie的两个应用

1.利用Cookie实现最近浏览的商品

books.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


商品列表

Java

Ajax

HTML

JavaScript

Spring

PHP

Android




显示最近浏览的商品

<% //显示最近浏览的商品 //获取所有的Cookie Cookie [] cookies = request.getCookies(); if(cookies != null && cookies.length > 0) { //从中筛选出cookie name是“Limbo's”的书籍 //显示cookie的value for(Cookie c : cookies) { if(c.getName().startsWith("Limbo_s_")) { out.println(c.getValue()); out.println("
"); } } } %>
book.jsp

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>




Insert title here

商品详情页

Book:<%= request.getParameter("bookName") %> return <% String bookName = request.getParameter("bookName"); //把书的信息以Cookie的形式回传给浏览器,删除一个Cookie //1.确定要删除的Cookie:以Limbo 's开头的Cookie Cookie[] cookies = request.getCookies(); //存放所有以Limbo's开头的cookie List cookieList = new ArrayList(); //存放和book.jsp传入的book匹配的Cookie Cookie tempCookie = null; if (cookies != null && cookies.length > 0) { for(Cookie c : cookies) { String cookieName = c.getName(); if(cookieName.startsWith("Limbo_s_")) { cookieList.add(c); } if(c.getValue().equals(bookName)) { tempCookie = c; } } } //数量大于等于5,或者是books.jsp中传入的book不在Cookie中, //则删除数组中最早的那个 if(cookieList.size() >= 5 && tempCookie == null) { tempCookie = cookieList.get(0); } if(tempCookie != null) { tempCookie.setMaxAge(0); //设置最大时间为0相当于删除 response.addCookie(tempCookie); //设置完了之后要回传,否则不会删除的 } //将book.jsp封装成一个cookie回传 Cookie cookie = new Cookie("Limbo_s_" + bookName, bookName); response.addCookie(cookie); %>

2.利用Cookie实现自动登录

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


	
cookie.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


	<%
		String name = request.getParameter("name");
		//可以获取登录者的名字,即通过登录到达指定页面
		if(name != null && !name.trim().equals(""))
		{
			Cookie cookie = new Cookie("username" , name);
			cookie.setMaxAge(30);//设置cookie的时效,让cookie在30秒内有效,即30秒内无需重复登录
			response.addCookie(cookie);//返回cookie
		}
		//之间访问指定页面
		else{
			Cookie[] cookies = request.getCookies();
			if(cookies != null && cookies.length > 0 )
			{
				for(Cookie cookie : cookies)
				{
					String cookieName = cookie.getName();
					//匹配键值
					if("username".equals(cookieName))
					{
						name = cookie.getValue();
					}
				}
			}
		}
		
		if(name != null && !name.trim().equals(""))
		{
			out.println("hello" + name);
		}
		else
		{
			response.sendRedirect("login.jsp");
		}
	%>





你可能感兴趣的:(JavaWeb)