• JavaEE Cookie HttpSession 学习笔记


    1. 会话管理概述

    1.1 什么是会话

    好比一次通话。打开浏览器,点击多次链接(发出多次请求和收到多次的响应),关闭浏览器,这个过程就是一次会话。

      有功能 可以  文件 新建会话  

      

    1.2 解决的问题是什么

    共享多次请求中产生的数据。比如购物车。

    1.3 Application Session Cookie 生命周期 简要区别

    方法

    信息量大小

    保存时间

    应用范围

    保存位置

    Application

    任意大小

    整个应用程序的生命期

    所有用户

    服务器端

    Session

    小量,简单的数据

    用户活动时间+一段延迟时间(一般为20分钟)

    单个用户

    服务器端

    Cookie

    小量,简单的数据

    可以根据需要设定

    单个用户

    客户端

    2. 客户端技术:Cookie

    2.1 HTTP协议的消息头

    请求消息头:Cookie 客户端向服务器端传递信息

    响应消息头:Set-Cookie 服务器端向客户端传递信息

    2.2 Cookie详解

    l  属性:

    name:Cookie的名称,必要的属性

    value:Cookie的取值(不能为中文),必要的属性

    -------------------以下为可选属性

    path:Cookie的路径

      默认值就是写cookie的那个资源的访问路径

      比如:http://localhost:8080/day09_00_cookie/servlet/CookieDemo1 path就是/day09_00_cookie/servlet/

      注意:

         如果一个存在浏览器缓存中的cookie的路径是/day09/servlet/

         当访问http://localhost:8080/day09/CookiePathDemo1时,

         浏览器根本不带Cookie给服务器。浏览器比对的是cookie的路径和当前访问的资源的路径。

         浏览器满足一下条件就会带cookie给服务器:

                当前访问的地址的路径.startWith(已存cookie的路径)。

                即:如果一个Cookie的路径设置为了当前应用,说明访问该网站的任何资源时浏览器都带该cookie给服务器。(开发中经常做的)

    maxAge:Cookie的最大生存时间。默认是在浏览器的内存中。

    domain:Cookie的域名(网站)。默认就是写cookie的那个资源所属的网站。

         http://localhost:8080/day09_00_cookie/servlet/CookieDemo1域名就是localhost

    version:版本号

    comment:注释

    u  把Cookie写给客户端:

    HttpServletResponse.addCookie(Cookie c):实际上就是向客户端发送了一个响应消息头。

    注意:客户端只能保存一个网站最多20个Cookie数据,总共最多300个。每个Cookie的大小不能超过4kb。

    l  服务器端获取客户端带来的Cookie:

    Cookie [] HttpServletRequest.getCookies();

    注意:domain+path+name唯一确定一个Cookie。

    2.3 3个案例

    2.3.1 显示用户最近的访问时间

    public class CookieDemo1 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		out.write("您上次访问的时间是:<a href='"+request.getContextPath()+"/servlet/ClearTimeServlet'>清除时间</a>");
    		
    		//获取指定名称的cookie:lastAccessTime=毫秒值
    		Cookie cs[] = request.getCookies();
    		for(int i=0;cs!=null&&i<cs.length;i++){
    			if("lastAccessTime".equals(cs[i].getName())){
    				//找到了
    				long time = Long.parseLong(cs[i].getValue());
    				out.write(new Date(time).toLocaleString());
    			}
    		}
    		
    		
    		//把当前的时间写回去
    		Cookie c = new Cookie("lastAccessTime", System.currentTimeMillis()+"");
    		c.setMaxAge(Integer.MAX_VALUE);//单位是秒
    		response.addCookie(c);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    
    //清除指定的cookie
    public class ClearTimeServlet extends HttpServlet {
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		//如何唯一定位要删除的cookie:domain+path+name
    		Cookie c = new Cookie("lastAccessTime", "");
    		c.setMaxAge(0);
    		response.addCookie(c);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    
    }
    

    演示Cookie的path

    public class CookiePathDemo1 extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //path:/day09/servlet/
            Cookie c = new Cookie("demoCookie", "aaa");
            c.setPath(request.getContextPath());// 把路径改为 /day09
            c.setMaxAge(Integer.MAX_VALUE);
    //        c.setDomain("itheima.com");//写了白写
            response.addCookie(c);
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    
    }
    
    public class CookiePathDemo2 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		Cookie cs[] = request.getCookies();
    		for(int i=0;cs!=null&&i<cs.length;i++){
    			if("demoCookie".equals(cs[i].getName())){
    				//找到了
    				response.getWriter().write(cs[i].getValue());
    			}
    		}
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    2.3.2 记住登录的用户名

    public class LoginUIServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		
    		String username = "";
    		String checked = "";
    		//得到指定的cookie
    		Cookie cs[] = request.getCookies();
    		for(int i=0;cs!=null&&i<cs.length;i++){
    			if("loginInfo".equals(cs[i].getName())){
    				username = cs[i].getValue();
    				checked="checked='checked'";
    				break;
    			}
    		}
    		
    		
    		out.write("<form action='"+request.getContextPath()+"/servlet/LoginServlet' method='post'>");
    		out.write("用户名:<input type='text' name='username' value='"+username+"'/><br/>");
    		out.write("密码:<input type='password' name='password' value=''/><br/>");
    		out.write("记住用户名:<input type='checkbox' name='remember' "+checked+"/><br/>");
    		out.write("<input type='submit' value='登录'/>");
    		out.write("</form>");
    		
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    public class LoginServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		
    		//验证用户名和密码是否正确:此处输什么都正确
    		String username = request.getParameter("username");
    		String password = request.getParameter("password");
    		String remember = request.getParameter("remember");//没有选中就是null
    		
    		Cookie c = new Cookie("loginInfo", username);
    		c.setPath(request.getContextPath());
    		if(remember==null){
    			//没有选中:删cookie
    			c.setMaxAge(0);
    		}else{
    			//用户记住用户名:存cookie
    			c.setMaxAge(Integer.MAX_VALUE);
    		}
    		response.addCookie(c);
    		out.write("登录成功");
    		
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    2.3.3 显示 最近浏览的产品 (图书)

    //book类
    public class Book { private String id; private String name; private String price; private String author; private String description; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", price=" + price + ", author=" + author + ", description=" + description + "]"; } public Book(String id, String name, String price, String author, String description) { super(); this.id = id; this.name = name; this.price = price; this.author = author; this.description = description; } public Book(){} }
    //模拟数据
    public class BookDB {
    	//key:书的id  value:id对应的书
    	private static Map<String,Book> books = new HashMap<String,Book>();
    	static{
    		books.put("1", new Book("1", "葵花宝典", "10", "nius", "欲练此功,必须很牛"));
    		books.put("2", new Book("2", "欲女心经", "2", "xuez", "欲练此功,必须清纯"));
    		books.put("3", new Book("3", "倾城之恋", "20", "liuc", "爱情经典"));
    		books.put("4", new Book("4", "辟邪剑法", "10", "wangl", "欲练此功,必须很牛"));
    		books.put("5", new Book("5", "JavaWeb开发", "100", "yif", "经典著作"));
    	}
    	public static Map<String,Book> findAllBooks(){
    		return books;
    	}
    	public static Book findById(String bookId){
    		return books.get(bookId);
    	}
    }
    
    public class ShowAllBooksServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		//显示所有的商品,提供查看详细内容的链接
    		out.write("<h1>本站有以下好书:</h1>");
    		
    		Map<String, Book> books = BookDB.findAllBooks();
    		for(Map.Entry<String, Book> me:books.entrySet()){
    			out.write(me.getValue().getName()+"  <a href='"+request.getContextPath()+"/servlet/ShowDetailsServlet?id="+me.getKey()+"' target='_blank'>查看详细</a><br/>");
    		}
    		
    		//显示最近的浏览记录:3条  bookHistory=2-1-3
    		out.write("<hr/>您最近的浏览记录如下:<br/>");
    		Cookie cs[] = request.getCookies();
    		for(int i=0;cs!=null&&i<cs.length;i++){
    			if("bookHistory".equals(cs[i].getName())){
    				String value = cs[i].getValue();// 2-1-3
    				String ids[] = value.split("\-");
    				for(String id:ids){
    					out.write(BookDB.findById(id).getName()+"<br/>");
    				}
    				
    				break;
    			}
    		}
    		
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    //显示商品的详细内容
    //组织数据,向客户端写cookie
    public class ShowDetailsServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		//显示商品的详细内容
    		
    		String id = request.getParameter("id");
    		Book book = BookDB.findById(id);
    		out.write(book.toString());
    		//组织数据,向客户端写cookie 3条  bookHistory=2-1-3
    		String bookId = makeId(id,request);
    		Cookie c = new Cookie("bookHistory", bookId);
    		c.setPath(request.getContextPath());
    		response.addCookie(c);
    		
    	}
    	//组织数据
    	
    	/*
    	客户端带来的cookie							当前访问的书的id			应该写回去的新id
    	cookie为null								1				bookHistory=1
    	cookie不为null,但没有bookHistory			1				bookHistory=1
    	bookHistory=1							2				bookHistory=2-1
    	bookHistory=1-2							3				bookHistory=3-1-2
    	bookHistory=1-2							2				bookHistory=2-1
    	bookHistory=1-2-3						4				bookHistory=4-1-2
    	bookHistory=1-2-3						2				bookHistory=2-1-3
    	 */
    	
    	private String makeId(String id, HttpServletRequest request) {
    //		cookie为null								1				bookHistory=1
    		Cookie cs[] = request.getCookies();
    		if(cs==null){
    			return id;
    		}
    //		cookie不为null,但没有bookHistory			1				bookHistory=1
    		Cookie bookHistoryCookie = null;
    		for(Cookie c:cs){
    			if("bookHistory".equals(c.getName())){
    				bookHistoryCookie = c;
    				break;
    			}
    		}
    		if(bookHistoryCookie==null){
    			return id;
    		}
    //		bookHistory=1							2				bookHistory=2-1
    //		bookHistory=1-2							3				bookHistory=3-1-2
    //		bookHistory=1-2							2				bookHistory=2-1
    		
    		String value = bookHistoryCookie.getValue();
    		String ids[] = value.split("\-");
    		LinkedList<String> list = new LinkedList<String>(Arrays.asList(ids));
    		
    		if(list.size()<3){
    			if(list.contains(id)){
    				list.remove(id);
    			}
    		}else{
    		
    //		bookHistory=1-2-3						4				bookHistory=4-1-2
    //		bookHistory=1-2-3						2				bookHistory=2-1-3
    			if(list.contains(id)){
    				list.remove(id);
    			}else{
    				list.removeLast();
    			}
    		}
    		list.addFirst(id);
    		
    		StringBuffer sb = new StringBuffer();
    		for(int i=0;i<list.size();i++){
    			if(i>0){
    				sb.append("-");
    			}
    			sb.append(list.get(i));
    		}
    		
    		return sb.toString();
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    3. 服务器端技术:HttpSession

    3.1 HttpSession是一个域对象及HttpSession的原理

      void setAttribute(String name,Object value);

      Object getAttribute(String name);

      void removeAttribute(String name);

      String getId()

      HttpSession request.getSession();

    //演示HttpSession的原理
    public class SessionDemo1 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		
    		String name = request.getParameter("name");
    		if(name==null){
    			out.write("请这样访问:http://192.168.33.172:8080/day09_01_HttpSession/servlet/SessionDemo1?name=abc");
    			return;
    		}
    		//得到HttpSession的实例
    		HttpSession session = request.getSession();
    		//在创建HttpSession对象的同时,服务器给这个对象分配一个唯一的ID(GUID)
    		System.out.println("SessionDemo1中HttpSession对象的id:"+session.getId());
    		session.setAttribute("p", name);
    		
    		out.write("放了。<a href='http://192.168.33.172:8080/day09_01_HttpSession/servlet/SessionDemo2'>去看看</a>");
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    public class SessionDemo2 extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		HttpSession session = request.getSession();
    		System.out.println("SessionDemo2中HttpSession对象的id:"+session.getId());
    		String v = (String)session.getAttribute("p");
    		response.getWriter().write(v);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    HttpSession request.getSession(boolean b):

    b如果为true,和getSession()完全一样的

    b为false,服务器只是查找,找不到不会创建新的,返回null。

    HttpSession.invalidate();使HttpSession对象立即失效。

    3.2 3个案例

    3.2.1 使用Session完成简单的购物功能

    使用上边的 book类 和 模拟 bookdb 数据

    public class Book implements Serializable

    //显示所有可购买的商品,提供购买链接
    //提供一个查看购物车的链接
    public class ShowAllBooksServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		
    		request.getSession();   //为了使 url 重写 
    		
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		//显示所有可购买的商品,提供购买链接
    		out.write("<h1>本站有以下好书:</h1>");
    		
    		Map<String, Book> books = BookDB.findAllBooks();
    		for(Map.Entry<String, Book> me:books.entrySet()){
    			String url = request.getContextPath()+"/servlet/BuyServlet?id="+me.getKey();
    			url = response.encodeURL(url);
    			out.write(me.getValue().getName()+"  <a href='"+url+"'>购买</a><br/>");
    		}
    		//提供一个查看购物车的链接
    		String url = request.getContextPath()+"/servlet/ShowCartServlet";
    		url = response.encodeURL(url);
    		out.write("<a href='"+url+"'>查看购物车</a>");
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    //把书籍放入购物车
    public class BuyServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		String id = request.getParameter("id");
    		Book b = BookDB.findById(id);
    		
    		//放到HttpSession中》用List来存
    		HttpSession session = request.getSession();
    		List<Book> cart = (List<Book>) session.getAttribute("cart");
    		if(cart==null){
    			cart = new ArrayList<Book>();
    			session.setAttribute("cart", cart);
    		}
    		//肯定有购物车
    		cart.add(b);
    		String url = request.getContextPath()+"/servlet/ShowAllBooksServlet";
    		url = response.encodeURL(url);
    		out.write(b.getName()+"已放入您的购物车<a href='"+url+"'>继续购物</a>");
    		
    		//为学习原理而做
    //		Cookie c = new Cookie("JSESSIONID", session.getId());
    //		c.setPath(request.getContextPath());
    //		c.setMaxAge(Integer.MAX_VALUE);
    //		response.addCookie(c);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    //显示购物车
    public class ShowCartServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		
    		HttpSession session = request.getSession();
    		List<Book> cart = (List<Book>)session.getAttribute("cart");
    		if(cart==null||cart.size()==0){
    			out.write("您还没有购买任何商品");
    			return;
    		}
    		
    		out.write("<h1>你购买的商品如下</h1>");
    		for(Book b:cart){
    			out.write(b.getName()+"<br/>");
    		}
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    3.2.2 完成用户的登录

    //user类
    public class User {
    	private String username;
    	private String password;
    	private String nickname;
    	public User(){}
    	
    	public User(String username, String password, String nickname) {
    		super();
    		this.username = username;
    		this.password = password;
    		this.nickname = nickname;
    	}
    	public String getUsername() {
    		return username;
    	}
    	public void setUsername(String username) {
    		this.username = username;
    	}
    	public String getPassword() {
    		return password;
    	}
    	public void setPassword(String password) {
    		this.password = password;
    	}
    	public String getNickname() {
    		return nickname;
    	}
    	public void setNickname(String nickname) {
    		this.nickname = nickname;
    	}
    	
    }
    
    public class UserDB {
    	private static List<User> users = new ArrayList<User>();
    	static{
    		users.add(new User("wzt", "123", "动感超油"));
    	}
    	public static User login(String username,String password){
    		for(User u:users){
    			if(u.getUsername().equals(username)&&u.getPassword().equals(password)){
    				return u;
    			}
    		}
    		return null;
    	}
    }
    
    //模拟主页
    public class IndexServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		
    		out.write("这是主页");
    		
    		HttpSession s = request.getSession();
    		User user = (User)s.getAttribute("user");//获取登录标记
    		if(user==null){
    			//说明没有登录
    			out.write("<a href='"+request.getContextPath()+"/servlet/LoginUIServlet'>登录</a>");
    		}else{
    			out.write("欢迎您:"+user.getNickname()+"<a href='"+request.getContextPath()+"/servlet/LogoutServlet'>注销</a>");
    		}
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    //提供登录界面
    public class LoginUIServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		out.write("<form action='"+request.getContextPath()+"/servlet/LoginServlet' method='post'>");
    		out.write("用户名: <input type='text' name='username' /><br/>");
    		out.write("密码: <input type='password' name='password' /><br/>");
    		out.write("验证码: <input type='text' name='code' /><img src='"+request.getContextPath()+"/servlet/ImageServlet'/><br/>");
    		out.write(" <input type='submit' value='登录' /><br/>");
    		out.write("</form>");
    		
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    //登录检
    public class LoginServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		String username = request.getParameter("username");
    		String password = request.getParameter("password");
    		User user = UserDB.login(username, password);
    		if(user==null){
    			out.write("错误的用户或密码,2秒后转向登录界面");
    			response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/servlet/LoginUIServlet");
    			return;
    		}
    		HttpSession session = request.getSession();
    		//验证码是否正确
    		String code = request.getParameter("code");
    		String scode = (String) session.getAttribute("code");
    		if(!code.equals(scode)){
    			out.write("错误的验证码,2秒后转向登录界面");
    			response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/servlet/LoginUIServlet");
    			return;
    		}
    		
    		//登录成功
    		session.setAttribute("user", user);
    		out.write("登录成功,2秒后转向主页");
    		response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/servlet/IndexServlet");
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    //注销
    public class LogoutServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		HttpSession session = request.getSession();
    //		session.invalidate();//立即失效
    		session.removeAttribute("user");
    		
    		out.write("注销成功,2秒后转向主页");
    		response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/servlet/IndexServlet");
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    public class ImageServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		int width = 120;
    		int height = 25;
    		//创建一副内存图像
    		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    		//得到画笔
    		Graphics g = image.getGraphics();
    			//开始画
    			//边线
    			g.setColor(Color.BLUE);
    			g.drawRect(0, 0, width, height);
    			//填充背景色
    			g.setColor(Color.YELLOW);
    			g.fillRect(1, 1, width-2, height-2);
    			//话干扰线
    			g.setColor(Color.GRAY);
    			
    			Random r = new Random();
    			for(int i=0;i<9;i++)
    				g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
    			//验证码
    			g.setColor(Color.RED);
    			g.setFont(new Font("宋体", Font.ITALIC|Font.BOLD, 19));
    //			String base = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48u8d77u4f60u90fdu628au597du8fd8u591au6ca1u4e3au53c8u53efu5bb6u5b66u53eau4ee5u4e3bu4f1au6837u5e74u60f3u751fu540cu8001u4e2du5341u4eceu81eau9762u524du5934u9053u5b83u540eu7136u8d70u5f88u50cfu89c1u4e24u7528u5979u56fdu52a8u8fdbu6210u56deu4ec0u8fb9u4f5cu5bf9u5f00u800cu5df1u4e9bu73b0u5c71u6c11u5019u7ecfu53d1u5de5u5411u4e8bu547du7ed9u957fu6c34u51e0u4e49u4e09u58f0u4e8eu9ad8u624bu77e5u7406u773cu5fd7u70b9u5fc3u6218u4e8cu95eeu4f46u8eabu65b9u5b9eu5403u505au53ebu5f53u4f4fu542cu9769u6253u5462u771fu5168u624du56dbu5df2u6240u654cu4e4bu6700u5149u4ea7u60c5u8defu5206u603bu6761u767du8bddu4e1cu5e2du6b21u4eb2u5982u88abu82b1u53e3u653eu513fu5e38u6c14u4e94u7b2cu4f7fu5199u519bu5427u6587u8fd0u518du679cu600eu5b9au8bb8u5febu660eu884cu56e0u522bu98deu5916u6811u7269u6d3bu90e8u95e8u65e0u5f80u8239u671bu65b0u5e26u961fu5148u529bu5b8cu5374u7ad9u4ee3u5458u673au66f4u4e5du60a8u6bcfu98ceu7ea7u8ddfu7b11u554au5b69u4e07u5c11u76f4u610fu591cu6bd4u9636u8fdeu8f66u91cdu4fbfu6597u9a6cu54eau5316u592au6307u53d8u793eu4f3cu58ebu8005u5e72u77f3u6ee1u65e5u51b3u767eu539fu62ffu7fa4u7a76u5404u516du672cu601du89e3u7acbu6cb3u6751u516bu96beu65e9u8bbau5417u6839u5171u8ba9u76f8u7814u4ecau5176u4e66u5750u63a5u5e94u5173u4fe1u89c9u6b65u53cdu5904u8bb0u5c06u5343u627eu4e89u9886u6216u5e08u7ed3u5757u8dd1u8c01u8349u8d8au5b57u52a0u811au7d27u7231u7b49u4e60u9635u6015u6708u9752u534au706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03u5973u4efbu4ef6u611fu51c6u5f20u56e2u5c4bu79bbu8272u8138u7247u79d1u5012u775bu5229u4e16u521au4e14u7531u9001u5207u661fu5bfcu665au8868u591fu6574u8ba4u54cdu96eau6d41u672au573au8be5u5e76u5e95u6df1u523bu5e73u4f1fu5fd9u63d0u786eu8fd1u4eaeu8f7bu8bb2u519cu53e4u9ed1u544au754cu62c9u540du5440u571fu6e05u9633u7167u529eu53f2u6539u5386u8f6cu753bu9020u5634u6b64u6cbbu5317u5fc5u670du96e8u7a7fu5185u8bc6u9a8cu4f20u4e1au83dcu722cu7761u5174u5f62u91cfu54b1u89c2u82e6u4f53u4f17u901au51b2u5408u7834u53cbu5ea6u672fu996du516cu65c1u623fu6781u5357u67aau8bfbu6c99u5c81u7ebfu91ceu575au7a7au6536u7b97u81f3u653fu57ceu52b3u843du94b1u7279u56f4u5f1fu80dcu6559u70edu5c55u5305u6b4cu7c7bu6e10u5f3au6570u4e61u547cu6027u97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u5e2eu5566u53d7u7cfbu4ee4u8df3u975eu4f55u725bu53d6u5165u5cb8u6562u6389u5ffdu79cdu88c5u9876u6025u6797u505cu606fu53e5u533au8863u822cu62a5u53f6u538bu6162u53d4u80ccu7ec6";
    			int x = 20;
    			StringBuffer sb = new StringBuffer();
    			for(int i=0;i<4;i++){
    				String num = r.nextInt(10)+"";
    				sb.append(num);
    				g.drawString(num, x,20 );
    //				g.drawString(base.charAt(r.nextInt(base.length()))+"", x, 20);
    				x+=18;
    			}
    			
    			request.getSession().setAttribute("code", sb.toString());
    			
    		//输出
    		response.setHeader("Expires", "-1");
    		response.setHeader("Cache-Control", "no-cache");
    		response.setHeader("Pragma", "no-cache");
    		ImageIO.write(image, "jpg", response.getOutputStream());
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    3.2.3 防止表单的重复提交

    //注册页面
    public class RegistUIServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		//产生一个唯一的ID(GUID就是UUID)
    //		String token = UUID.randomUUID().toString();
    		String token = new BigInteger(165, new Random()).toString(36).toUpperCase();//GUID
    		
    		request.getSession().setAttribute("token", token);
    		
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		out.write("<form action='/day09_01_HttpSession/servlet/RegistServlet' method='post'>");
    		out.write("姓名:<input name='name'/><br/>");
    		out.write("<input type='hidden' name='token' value='"+token+"'/><br/>");
    		out.write("<input type='submit' value='保存'/></form>");
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    public class RegistServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=UTF-8");
    		PrintWriter out = response.getWriter();
    		String name = request.getParameter("name");
    //		try {
    //			Thread.sleep(1000);
    //		} catch (InterruptedException e) {
    //			e.printStackTrace();
    //		}//模拟网络慢
    		
    		String stoken = (String) request.getSession().getAttribute("token");
    		String ftoken = request.getParameter("token");
    		if(ftoken.equals(stoken)){
    			System.out.println(name);
    			request.getSession().removeAttribute("token");
    		}else{
    			out.write("请不要重复提交");
    		}
    		
    		
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    

    3.3 客户端禁用Cookie后的会话数据的保持

    客户端永远不会向服务器端带任何cookie。

    解决办法:

    方式一:(乌龙)文字提示:请不要禁用您的Cookie

    方式二:在访问的地址后面加上JSESSIONID=session的id。

    http://localhost:8080/servlet/ServletDemo1   URL重写,必须对网站的所有地址都重写

    http://localhost:8080/servlet/ServletDemo1;JSESSIONID=123

    response.encodeUrl(String url);自动重写。 对购物车案例 修改了

    3.4 HttpSession对象的状态

    很多 银行的保护性就是将session 减短了。

    public class Book implements Serializable 序列化

    4 总结

    一、会话概述
        1、如同一次电话通话。
        2、会话中要解决的问题:多次请求中的数据的保持问题。典型:购物车
    二、Cookie
        1、属性:
            name value path maxAge domain version 等
        2、HttpServletResponse.addCookie(Cookie c)
        3、HttpServletRequest.getCookies()
        4、记住用户名和记住用户的浏览记录
    三、HttpSession
        1、HttpSession是一个域对象
        2、HttpSession的原理(借助Cookie)
        3、HttpSession.getSession():先查(按照session对象的ID去查),没有再创建。
        4、案例:
            简单购物车
            用户登录和验证码验证
            防止表单的重复提交:从原理上明白
        5、客户端禁用了Cookie后的会话数据保持问题
            URL重写
        6、HttpSession对象的状态变化:钝化和激活。   向HttpSession中存放的对象的类,要实现java.io.Serializable接口
        7、浏览器何时会开启一次新的会话。
       

  • 相关阅读:
    CentOS7安装Docker
    centos7上安装rar解压软件
    Docker自定义镜像Tomcat8
    Docker 安装mysql 5.6
    Linux中~ / /home /root之间的区别于联系
    如何下载Steam游戏
    Matplotlib系列转载
    资料积累一:面对TDLAS气体传感系统的锁相放大技术研究
    双人游戏
    PyCharm+PyQt5+QtDesigner配置(三)
  • 原文地址:https://www.cnblogs.com/loveincode/p/5218060.html
Copyright © 2020-2023  润新知