JavaEE实战——会话与状态 Cookie_Session

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhongkelee/article/details/52420034

前言

本篇博客是Servlet入门的第三篇博客,主要详述JavaEE中的会话与状态 ---- Cookie和Session。首先快速教大家jsp、el、jstl入门,后一篇博客详述这种技术。

JSP 快速入门

Servlet技术 用来动态生成 网页数据资源,Servlet生成HTML 页面数据时,所有内容都是通过 response.getWriter  response.getOutputStream 向浏览器输出的。比如我们写一个如下的html文件:

<span style="font-size:14px;"><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
	h1{
		color:red;
	}
</style>
<script type="text/javascript">
	alert(1);
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html></span>

那如果我们使用Servlet 输出流打印网页信息,则要使用 response.getWriter().print("<html>"); 如:

package ustc.lichunchun.servlet.demo1;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.getWriter()
				.println(
						"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
		response.getWriter().println("<html>");
		response.getWriter().println("<head>");
		response.getWriter().println(
				"<style type=\"text/css\">h1{color:red;}</style>");
		response.getWriter().println("</head>");
		response.getWriter().println("<body>");
		response.getWriter().println("<h1>Hello</h1>");
		response.getWriter().println("</body>");
		response.getWriter().println("</html>");
	}

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

}

Servlet生成网页缺点

1、通过print输出网页 开发很不方便

2、美工人员经常对页面进行CSS修饰,美工人员在java代码中调试CSS

3、无法使用开发工具对页面代码进行调试 JS CSS 

98前后 主流网页设计技术 ASP PHP , sun推出Servlet,sun参考ASP语法推出JSP (Java Server Pages)

* 什么是 JSP ? JSP 和Servlet技术一样,都是动态网页开发技术 ,是在服务器端执行的

* JSP 和 Servlet 关系? JSP在运行时,需要先翻译为Servlet才能运行  ------ JSP 就是 Servlet 

Servlet2.5 版本 ---- JavaEE 5.0  ---- JSP 版本2.1 

Servlet3.0 版本 ---- JavaEE 6.0  ---- JSP 版本2.2 

编写第一个JSP程序

1、JSP位于WebRoot下 --- 不能放入WEB-INF(不能访问)
2、修改JSP默认编码   window --- preferences --- JSP 修改编码 utf-8
3、修改JSP 默认编辑器 window --- preferences --- general ---- editor ---- File Associations  将 JSP编辑器改为 JSP Editor
4、在WebRoot下 新建 JSP ---- hello.jsp 
5、写JSP过程和编写HTML一样,可以通过<%%> 嵌入java代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	//嵌入java程序
	String s = "你好!Java Server Pages!";
	//通过 out对象 将 s内容显示在浏览器上
	out.println(s);
%>
<h1>Hello JSP</h1>
</body>
</html>

* 有人比喻 Servlet:嵌入HTML的java文件 ; JSP :嵌入Java的HTML文件 

JSP运行原理

1、客户端访问hello.jsp
2、服务器读取hello.jsp内容到内存
3、服务器根据hello.jsp内容生成Servlet程序 ----保存在哪? tomcat/work 
4、Servlet编译运行 


JSP翻译Servlet 固定包名 :org.apache.jsp 

hello.jsp ---- hello_jsp.java

我们来看一下 apache/work 目录下对应的 hello_jsp.java

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.42
 * Generated at: 2016-08-30 13:21:12 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class hello_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html; charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
      out.write("<title>Insert title here</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");

	//嵌入java程序
	String s = "你好!Java Server Pages!";
	//通过 out对象 将 s内容显示在浏览器上
	out.println(s);

      out.write("\r\n");
      out.write("<h1>Hello JSP</h1>\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

注:hello.jsp翻译成hello_jsp.java后,我们看tomcat/work/day07/org/apache/jsp/hello_jsp.java文件,发现其继承org.apache.jasper.runtime.HttpJspBase类。再通过查看apache源码,发现HttpJspBase继承HttpServlet类,真相大白,服务器端tomcat引擎的确是将jsp文件翻译为了Servlet文件。

JSP程序的翻译过程

JSP中 HTML代码、<%%> 代码都会被翻译Servlet 中 _jspService 方法里

翻译规则

1、JSP 中 HTML 翻译 out.write
2、JSP 中 java 代码 不会翻译 


JSP中脚本元素

1、声明 <%! %> --- 定义内容将会被翻译Servlet类、成员变量和方法,声明的作用范围是整个JSP页面,同时它只在一个JSP页面有效 

2、表达式 <%= %> ---- 用于向页面输出内容,等价于 out.print(),表达式的计算结果转换成字符串,JSP脚本表达式中的变量或表达式后面不能有分号(;)

3、代码块<% %> --- 在<%%> 之间编写任何java代码,一个JSP页面可以有许多代码块,这些代码块将被JSP服务器按照顺序执行,在一个代码块中声明的变量是JSP页面的局部变量,只在当前页面有效
* 注:代码块可以和html嵌套使用


举例:

init.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- JSP语法 脚本元素三种 -->
<h1>JSP 脚本</h1>
<!-- 第一种  JSP脚本声明 -->
<%!
	int a = 10;
	public void print(){}
	class A{}
%>
<!-- 第二种  脚本表达式 输出内容到页面 -->
<%= "abcd" %>
<% out.print("abcd"); %>
<!-- 第三种 代码块 编写任何java程序 -->
<%
	for(int i = 0; i < 10; i++){
		out.print(i);
	}
%>
<%
	for(int i = 0; i < 10; i++){
%>
	<h1>代码块中间可以编写HTML 即代码块可以和html嵌套使用</h1>
<%
	}
%>
</body>
</html>

init.jsp 在 tomcat/work 下对应的 init_jsp.java 文件:

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.42
 * Generated at: 2016-08-30 14:02:01 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp.jsp.demo1;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class init_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {


	int a = 10;
	public void print(){}
	class A{}

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html; charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
      out.write("<title>Insert title here</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("<!-- JSP语法 脚本元素三种 -->\r\n");
      out.write("<h1>JSP 脚本</h1>\r\n");
      out.write("<!-- 第一种  JSP脚本声明 -->\r\n");
      out.write("\r\n");
      out.write("<!-- 第二种  脚本表达式 输出内容到页面 -->\r\n");
      out.print( "abcd" );
      out.write('\r');
      out.write('\n');
 out.print("abcd"); 
      out.write("\r\n");
      out.write("<!-- 第三种 代码块 编写任何java程序 -->\r\n");

	for(int i = 0; i < 10; i++){
		out.print(i);
	}

      out.write('\r');
      out.write('\n');

	for(int i = 0; i < 10; i++){

      out.write("\r\n");
      out.write("\t<h1>代码块中间可以编写HTML 即代码块可以和html嵌套使用</h1>\r\n");

	}

      out.write("\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

开发网页程序,使用Servlet? 使用JSP呢?

Java代码多 --- Servlet

HTML代码多 ---- JSP

JSP运行时 总要翻译Servlet ,效率很低 ?

* 只有第一次访问JSP 进行翻译 ,以后访问,如果没有修改 JSP 不会重新翻译 

EL快速入门

EL 全名为 Expression Language  ---- 表达式语言

常用功能:获取各种域中存储的数据

语法:${标识符}

${applicationScope.name }  等价于 <%=getServletContext().getAttribute("name") %>
${requestScope.address }  等价于 <%=request.getAttribute("address") %>

代码示例:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- EL 可以获得 Servlet 数据域对象值 -->
<%
	getServletContext().setAttribute("name", "李春春");
	request.setAttribute("school", "中国科学技术大学");
%>
<h1>取得ServletContext和request中数据</h1>
<%=getServletContext().getAttribute("name") %>
<%=request.getAttribute("school") %>

<h1>通过EL 取得 ServletContext和request中数据 </h1>
${applicationScope.name }
${requestScope.school }
</body>
</html>

JSTL快速入门

JSTL (JSP Standard Taglib Liberary) --- JSP 标准标签库 

JSTL干嘛用的? 简化页面<%%> 与 HTML嵌套写法  ----- 简化JSP开发 

本博客主要需要用到如下两个: <c:forEach> <c:if>  ----- 用来替换页面中for循环 和 if条件判断 

在页面内使用JSTL 简化 if 和 for 

1、导入jstl的jar包  --- MyEclipse中存在 javaee5 类库 --- 存在 jstl1.2.jar 
2、在jsp页面最上方声明使用JSTL core标签库 <%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%> 
* 定义了很多标签,为标签指定名称空间 uri ,在使用标签前 引用名称空间

JSTL+EL 简化 <%%> 脚本代码,示例:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>在页面内 编写if条件判断</h1>
<%
	int a = 10;
	if(a > 8){
%>
	a的值大于8
<%		
	}
%>
<h1>使用 c:if 替换上面 if判断</h1>
<%
	request.setAttribute("b", 12);
%>
<!-- b在request 通过EL -->
<c:if test="${requestScope.b > 10 }">
	b的值大于10
</c:if>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>     
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>通过 % 编写传统 foreach循环</h1>
<%
	int[] arr = {1,2,3,4,5,6};
	for(int i : arr){
%>
		i的值是:<%=i %><br/>
<%		
	}
%>
<h1>通过 jstl中 c:foreach 替代上面循环</h1>
<%
	request.setAttribute("arr", new int[]{7,8,9,10,11,12});
%>
<!-- item编译目标集合 -->
<c:forEach items="${requestScope.arr }" var="i">
	i的值是:${i }<br/>
</c:forEach>
</body>
</html>


会话管理

什么是会话? 用户打开浏览器,访问站点,连续进行多次操作,关闭浏览器 ,整个过程称为会话 。

会话状态不管理将导致问题:


HTTP协议是无状态的,但是通过购物的例子可以看出现在的需求是,需要在服务器端管理客户端的会话状态,为了解决这个会话状态管理的问题,我们引入Cookie和Session技术。

* 什么是有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学曾经来过,这称之为有状态会话。

思考:用户购买的商品保存在request或servletContext中行不行?不行!

    |--如果使用request保存用户购买数据 --- 第一次request请求用户购买笔记本,当发送第二次request请求购买洗衣机时,之前一次request请求对象中保存的笔记本数据丢失。
    |--如果张三买笔记本,李四买手机,用servletContext对象保存数据,所有数据保存在同一个Context对象中 --- 谁付款,需要为所有用户商品付钱。

管理HTTP协议会话状态 :Cookie 和Session  

Cookie:将用户相关数据,保存客户端 , 用户每次访问服务器自动携带cookie数据 。
Session :将用户相关数据,保存服务器端,为每个客户端生成一个独立Session数据对象,通过对象唯一编号,区分哪个浏览器对应 哪个Session

cookie和session区别



Cookie技术


Cookie技术原理


Cookie快速入门

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


1、通过服务器向客户端写cookie
Cookie cookie = new Cookie(name,value);
response.addCookie(cookie); 
* 在HTTP协议响应头信息中 Set-Cookie: last=1339556457609

2、当客户端存在cookie之后,以后每次请求自动携带 HTTP协议请求头信息 Cookie: last=1339556456859

服务器端获得需要cookie数据
Cookie[] cookies = request.getCookies(); ---- 获得客户端所有cookie
if(cookies==null){}  判断cookie是否存在

遍历cookie获得需要信息

for (Cookie cookie : cookies) {
    // 获得每个cookie
    if (cookie.getName().equals("last")) {
        // 找到了需要cookie
    }
}

代码:

package ustc.lichunchun.servlet.cookie.demo1;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 完成上次访问时间查看,显示给用户
 */
public class LastVisitServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", -1);
		response.setHeader("Pragma", "no-cache");
		
		// 如果用户第一次访问 ---- 判断请求中有没有cookie信息
		Cookie[] cookies = request.getCookies();// 获得请求中所有cookie信息
		
		response.setContentType("text/html;charset=utf-8");
		
		if(cookies == null){
			// 没有cookie 第一次访问
			// 将当前时间 以cookie写回客户端

			// 当前时间毫秒 等价 new Date().getTime()
			long now = System.currentTimeMillis();
			
			// 向客户端写出cookie 需要用到cookie API
			Cookie cookie = new Cookie("last", now+"");
			
			cookie.setPath("/day07");

			// 设置cookie 有效时间
			cookie.setMaxAge(60*60*24*2);// 设置cookie 时间两天
			
			// 写cookie回到客户端
			response.addCookie(cookie);
			
			// 通知用户 第一次访问
			response.getWriter().println("欢迎您第一次访问本网站,购物愉快!");
		}else{
			// cookie存在 ---- 获得最后访问时间
			for (Cookie cookie : cookies) {
				// 获得每个cookie
				if(cookie.getName().equals("last")){
					long lasttime = Long.parseLong(cookie.getValue());
					// 显示给用户
					Date date = new Date(lasttime);
					
					// 格式化日期
					DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
					
					response.getWriter().println("上次访问时间 :" + dateFormat.format(date));
				}
			}
			
			// 更新最后访问时间

			// 当前时间毫秒 等价 new Date().getTime()
			long now = System.currentTimeMillis();
			
			// 向客户端写出cookie 需要用到cookie
			Cookie cookie = new Cookie("last", now+"");
			
			cookie.setPath("/day07");

			// 设置cookie 有效时间
			cookie.setMaxAge(60*60*24*2);// 设置cookie 时间两天
			
			// 写cookie回到客户端
			response.addCookie(cookie);
		}
	}

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

}

结果:




Cookie API 详解

javax.servlet.http.Cookie类用于创建一个Cookie,response接口中也定义了一个addCookie方法,它用于在其响应头中增加一个相应的Set-Cookie头字段。
同样,request接口中也定义了一个getCookies方法,它用于获取客户端提交的Cookie。

Cookie类的方法

    |--public Cookie(String name, String value)
    |--setValue与getValue方法
    |--setMaxAge与getMaxAge方法
    |--setPath与getPath方法
    |--setDomain与getDomain方法
    |--getName方法

下面我详述这几组方法: 

1、将cookie写回客户端 response.addCookie(cookie);

2、读取请求中 cookie信息 request.getCookies 

3、Cookie对象创建 new Cookie(name,value )

* cookie的name 不允许改变   ----- getName 、getValue 、setValue

4、什么是会话cookie ,什么是持久cookie ?

cookie信息默认情况 保存在浏览器内存中 ------ 会话cookie 
会话cookie 会在关闭浏览器时 清除
实验:两次打开浏览器,输入:http://localhost/day07/lastvisit,结果均是欢迎光临!

持久Cookie,cookie数据保存客户端硬盘上 

通过setMaxAge 设置Cookie为 持久Cookie
cookie.setMaxAge(60 * 60 * 24 * 2);// 设置cookie 时间两天,这时在浏览器的缓存目录中会有该Cookie的文件存在
* 注:在JavaAPI 中所有与时间相关参数,int 类型 单位秒, long类型 单位毫秒
实验:加了cookie.setMaxAge(int)后,两次打开浏览器,输入:http://localhost/day07/lastvisit,结果第一次是欢迎光临,第二次是上次登陆时间!

5、访问cookie有效路径path

默认情况下,生成cookie时,产生默认有效访问路径 (默认生成cookie程序路径)

http://localhost/day07/lastvisit  --- 生成cookie  --- path 默认值: /day07 

http://localhost/day07/servlet/path ---- 生成cookie ---- path 默认值:/day07/servlet 

package ustc.lichunchun.servlet.cookie.demo2;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 通过程序生成cookie 设置有效路径path
 */
public class PathCookieServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Cookie cookie = new Cookie("school", "ustc");
		cookie.setMaxAge(60*60);
		// 手动设置path
		cookie.setPath("/day07");
		response.addCookie(cookie);
		
		//一个WEB站点可以给一个WEB浏览器发送多个Cookie
		Cookie cookie2 = new Cookie("address", "hefei");
		cookie2.setMaxAge(60 * 60);
		cookie2.setPath("/day07");
		response.addCookie(cookie2);
	}

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

}

实验:首先访问这两个站点,保证本地硬盘都保存了Cookie信息。然后打开两个浏览器,第一个里访问lastvisit,第二个里访问path,分别查看请求报文。


第二次访问程序携带cookie信息,如果访问路径与path不一致,不会携带cookie 信息 

last cookie : path --- /day07
company cookie : path --- /day07/serlvet

访问 :http://localhost/day07/servlet/path ---- 同时满足/day07/serlvet、/day07 -- 携带 company 和 last 两个cookie信息

访问 :http://localhost/day07/lastvisit  ---- 满足 /day07 不满足/day07/serlvet -- 携带 last 一个cookie 信息

但是当我们在PathCookieServlet.java中使用了cookie.setPath("/day07")之后,就可以在lastvisit的cookie里也携带两个信息了

* 结论:以后程序开发,尽量设置path ---- setPath方法 

6、第一方cookie 和 第三方cookie 

通过setDomain 设置cookie 有效域名 
访问google时,生成cookie过程中 cookie.setDomain(".baidu.com") ---- 生成百度cookie ------ 第三方cookie 

* 第三方cookie 属于不安全  ----- 一般浏览器不接受第三方cookie 


访问google时,生成cookie,cookie.setDomain(.google.con) ---- 生成google的cookie ------ 第一方cookie 

Cookie细节

一个Cookie只能标识一种信息,它至少含有一个标识该信息的名称(NAME)和设置值(VALUE)。 
一个WEB站点可以给一个WEB浏览器发送多个Cookie,一个WEB浏览器也可以存储多个WEB站点提供的Cookie。
浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4KB。
如果创建了一个cookie,并将他发送到浏览器,默认情况下它是一个会话级别的cookie(即存储在浏览器的内存中),用户退出浏览器之后即被删除。若希望浏览器将该cookie存储在磁盘上,则需要使用maxAge,并给出一个以秒为单位的时间。将最大时效设为0则是命令浏览器删除该cookie。

注意,删除cookie时,path必须一致,否则不会删除 (默认:产生cookie服务器资源所在path)

持久Cookie的删除

案例:删除上次访问时间

原理:设置cookie MaxAge为 0 
 * 删除cookie时 必须设置path 与cookie的 path一致
package ustc.lichunchun.servlet.cookie.demo3;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
 * 删除上次访问时间
 */
public class DeleteCookieServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Cookie cookie = new Cookie("last", "");
		
		// 删除持久化cookie -- 设置有效期 0
		cookie.setMaxAge(0);
		
		// 要保证path一致
		cookie.setPath("/day07");
		
		response.addCookie(cookie);
	}

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

}

实验:

在LastVisitServlet.java中加上三行不缓存代码,然后浏览器先访问/day07/lastvisit,本地硬盘生成持久Cookie,然后在访问/day07/delete,因为DeleteCookieServlet.java中设置了cookie.setMaxAge(0),所以删除了对应该有效路径path的持久Cookie, 此时,你再一次访问/day07/lastvisit,又会显示欢迎购物!


Cookie应用

案例:商品浏览记录显示及清空 ---- 可以通过Cookie实现

显示上次浏览商品的实现过程:


多条商品浏览记录及清空浏览记录--原理分析:


代码:

<%@page import="ustc.lichunchun.utils.CookieUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 页面由两部分组成 -->
<h1>商品列表</h1>
<a href="/day07/producthistory?id=1">冰箱</a><br>
<a href="/day07/producthistory?id=2">洗衣机</a><br/>
<a href="/day07/producthistory?id=3">笔记本电脑</a><br/>
<a href="/day07/producthistory?id=4">手机</a><br/>
<a href="/day07/producthistory?id=5">空调</a><br/>
<a href="/day07/producthistory?id=6">热水器</a><br/>
<a href="/day07/producthistory?id=7">微波炉</a><br/>
<a href="/day07/producthistory?id=8">电风扇</a><br/>

<h1>商品浏览记录</h1><h3><a href="/day07/cleanhistory">清空浏览记录</a></h3>
<%
	/*
	Cookie[] cookies = request.getCookies();
	if(cookies == null){
		out.println("无浏览记录!");
	}else{
		for(Cookie c: cookies){
			if(c.getName().equals("history")){
				String id = c.getValue();
				String[] arr = { "冰箱", "洗衣机", "笔记本电脑", "手机", "空调", "热水器", "微波炉", "电风扇" };
				out.println(arr[Integer.parseInt(id) - 1]);
			}
		}
	}
	*/
	Cookie cookie = CookieUtils.findCookie(request.getCookies(), "history");
	if(cookie == null){
		out.println("无浏览记录!");
	}else{
		String ids = cookie.getValue();
		String[] idArray = ids.split(",");
		String[] arr = { "冰箱", "洗衣机", "笔记本电脑", "手机", "空调", "热水器", "微波炉", "电风扇" };
		for(String id: idArray){
			out.println(arr[Integer.parseInt(id) - 1] + "<br/>");
		}
	}
%>
</body>
</html>
package ustc.lichunchun.utils;

import javax.servlet.http.Cookie;
/**
 * 经常读取Cookie,每次读取需要执行for循环,将读取cookie操作抽取出来
 */
public class CookieUtils {
	/**
	 * 在Cookie数组中 查找指定name cookie
	 */
	public static Cookie findCookie(Cookie[] cookies, String name){
		if(cookies == null){// 没有cookie
			return null;
		}else{
			for(Cookie cookie : cookies){
				if(cookie.getName().equals(name)){
					return cookie;
				}
			}
			return null;
		}
	}
}
package ustc.lichunchun.servlet.cookie.demo4;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ustc.lichunchun.utils.CookieUtils;
/**
 * 浏览商品 ,将商品浏览记录添加 Cookie
 */
public class ProductHistoryServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String[] arr = { "冰箱", "洗衣机", "笔记本电脑", "手机", "空调", "热水器", "微波炉", "电风扇" };
		
		// 1 获得用户点击查看商品 编号
		String id = request.getParameter("id");
		
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println("用户正在浏览商品:" + arr[Integer.parseInt(id) - 1]);
		response.getWriter().println("<a href='/day07/cookie/demo4/product.jsp'>返回</a>");
		
		// 读取客户端cookie
		Cookie cookie = CookieUtils.findCookie(request.getCookies(), "history");
		if(cookie == null){
			// 没有浏览记录
			cookie = new Cookie("history", id);
			cookie.setMaxAge(60*60);
			cookie.setPath("/day07");
			// 3、写回cookie
			response.addCookie(cookie);
		}else{
			// 已经存在商品浏览记录,判断当前浏览商品是否已经在记录中
			String ids = cookie.getValue();
			String[] idArray = ids.split(",");
			for(String  existId : idArray){
				if(existId.equals(id)){
					// 当前浏览商品 已经在浏览器记录中
					return;
				}
			}
			
			// 当前id没有在浏览记录中
			cookie.setValue(ids + "," + id);
			cookie.setMaxAge(60*60);
			cookie.setPath("/day07");
			// 3、写回cookie
			response.addCookie(cookie);
		}
	}

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

}
package ustc.lichunchun.servlet.cookie.demo4;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 清除 history的cookie信息
 */
public class CleanHistoryServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Cookie cookie = new Cookie("history", "");
		
		// 设置MaxAge 为0
		cookie.setMaxAge(0);
		
		// path一致
		cookie.setPath("/day07");
		
		response.addCookie(cookie);
		
		//request.getRequestDispatcher("/cookie/demo4/product.jsp").forward(request, response);
		//转发是无效的,因为转发是一次请求一次响应,当你在product.jsp页面点击清空浏览记录时
		//你的请求报文没有变,request.getCookies()得到的还是history=1
		//此时,request是history=1,response是history="",根据product.jsp代码,显示浏览记录读取的是request.getCookies
		//所以要想生效,必须再次刷新product.jsp,使得cleanhistory中的response设定history=""在客户端cookie生效
		//从而使得request请求报文中的request.getCookies()得到null
		
		response.sendRedirect("/day07/cookie/demo4/product.jsp");
		//跳转到商品列表页,重定向就不存在转发的问题,因为是多次请求多次响应
		//此时你在priduct.jsp页面点击清除浏览记录,会将history=1的request发送到cleanhistory
		//cleanhistory的response设定为history=""后,由于你是用的是重定向,所以会将这个response返回到客户端
		//客户端收到response后更新本地cookie中的history=""
		//然后因为是302重定向,再次向product.jsp页面发送request,此时已是history="",故product.jsp页面上不会再显示浏览记录
	}

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

}
结果展示:




Session技术

Session 是服务器端会话管理技术,服务器会为每个浏览器创建一个单独Session对象,保存该浏览器(会话)操作相关信息。

Session原理


Session对象由服务器创建,开发人员可以调用request对象的getSession方法得到session对象。

* 若request报文头信息Cookie中没有JSESSIONID,则服务器端创建一个Session对象,并返回给浏览器一个对应的JSESSIONID的cookie (这其中IE6默认是会话级别cookie)
* 若request报文头信息Cookie中有JSESSIONID,则通过该JSESSIONID,找服务器端对应的Session对象


Session与Cookie区别:cookie是保存在客户端,Session保存在服务器端 

为什么有Cookie技术?还需要Session ?

Cookie 存在客户端 ---- 存在安全问题 
Session将数据存在服务器,数据更加安全 
* Session将数据保存在服务器端,占用服务器内存资源 ,Cookie不会占用服务器资源 

例如:京东购物车信息 保存Cookie 、淘宝购物车信息保存Session

Session原理与共享

实验:
1、用IE6 向Session保存一个数据,用另一个IE6读取数据?
用第一个IE6保存session数据,当前浏览器可以获得,但是第二个IE6 无法获得第一个浏览器保存Session 数据
IE8以上 或 火狐浏览器:当打开多个浏览器窗口,之间Session共享。

原因:IE6 cookie 中保存jsessionId 默认会话级别 ;IE8或者火狐 保存cookie中 jsessionId 默认持久cookie

问题:如何让多个IE6 共享同一个Session?  ---- 将写回给 浏览器的 session id 持久化 
Cookie cookie = new Cookie("JSESSIONID", httpSession.getId());
cookie.setMaxAge(60 * 60);
cookie.setPath("/day07");
response.addCookie(cookie);

代码示例:

package ustc.lichunchun.servlet.session.demo1;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 向session 保存一个数据
 */
public class WriteSessionServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得Session对象
		// Session对象由服务器创建,开发人员可以调用request对象的getSession方法得到session对象
		// 若request头信息Cookie中没有JSESSIONID,则服务器端创建一个Session对象,并返回给浏览器一个对应的JSESSIONID的cookie
		HttpSession httpSession = request.getSession();
		
		// 向session 保存一个数据
		httpSession.setAttribute("school", "中国科学技术大学");
		
		// 将写回给 浏览器的 JSESSIONID 持久化,否则IE6默认是会话级别cookie
		Cookie cookie = new Cookie("JSESSIONID", httpSession.getId());
		cookie.setMaxAge(60*60);
		cookie.setPath("day07");
		response.addCookie(cookie);
		
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println("已经向session保存了一个数据!");
	}

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

}
package ustc.lichunchun.servlet.session.demo1;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 读取 WriteSessionServlet 保存数据
 */
public class ReadSessionServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得Session对象
		// 若request报文的Cookie头信息中有JSESSIONID,则找服务器端对应的Session对象
		HttpSession httpSession = request.getSession();
		
		response.setContentType("text/html;charset=utf-8");
		
		// 获得数据
		response.getWriter().println("读取之前保存session信息 :" + httpSession.getAttribute("school"));
	}

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

}

搞懂上面的 session id 持久化之后,下面问两个常见面试题:

问题:如果客户端关闭浏览器,是否就删除了Session ?
没有,Session保存在服务器端

问题:IE6 保存Session,关闭浏览器,再次打开,数据丢失了?

IE6默认jsessionId保存在会话Cookie中,关闭浏览器,会话cookie就会被删除,客户端丢失jsessionid 无法找到服务器对应Session对象。但实际上,服务器Session对象还存在

Session购物车案例

1、商品列表,用户点击列表中商品,将商品添加购物车
2、查看购物车中商品,以及商品购买件数

原理分析:


代码示例:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>商品列表</h1>
冰箱  <a href="/day07/buy?id=1">加入购物车</a> <br/> 
洗衣机  <a href="/day07/buy?id=2">加入购物车</a> <br/> 
热水器  <a href="/day07/buy?id=3">加入购物车</a> <br/> 
微波炉  <a href="/day07/buy?id=4">加入购物车</a> <br/> 
空调  <a href="/day07/buy?id=5">加入购物车</a> <br/> 
电饭锅  <a href="/day07/buy?id=6">加入购物车</a> <br/> 
</body>
</html>
package ustc.lichunchun.servlet.session.demo2;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 添加商品到购物车
 */
public class BuyServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、获得购买商品编号
		String id = request.getParameter("id");
		
		// 2、根据编号 得到商品名称
		String[] arr = {"冰箱","洗衣机","热水器","微波炉","空调","电饭锅 "};
		String productName = arr[Integer.parseInt(id)-1];
		
		// 3、判断商品名称是否在购物车中
		// 判断购物车是否存在
		Map<String, Integer> cart = (Map<String, Integer>)request.getSession().getAttribute("cart");// 可能返回 null
		if(cart == null){
			// 购物车对象不存在
			cart = new HashMap<String, Integer>();
		}
		
		if(cart.containsKey(productName)){
			// 购物车存在该商品 数量+1
			int num = cart.get(productName);
			cart.put(productName, num+1);
		}else{
			// 商品没有在购物车中
			cart.put(productName, 1);
		}
		
		// 将购物车加入session
		request.getSession().setAttribute("cart", cart);
		
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println(productName + "商品已经被加入购物车!");
		response.getWriter().println("<a href='/day07/session/demo2/cart.jsp'>查看购物车</a>");
	}

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

}
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>查看购物车</h1>
<!-- 购物车信息保存 session中 Map<String,Integer> -->
<%
	Map<String, Integer> cart = (Map<String, Integer>)request.getSession().getAttribute("cart");
	if(cart == null){
		out.println("无购物信息");
	}else{
		for(String productName : cart.keySet()){
			out.println("<h3>商品名称:"+productName+" ,数量:"+cart.get(productName)+" </h3>");
		}
	}
%>
<hr/>
<!-- 通过JSTL+EL 编写Map集合 -->
<c:if test="${empty sessionScope.cart }">
	无购物信息
</c:if>
<c:if test="${not empty sessionScope.cart }">
	<!-- 遍历 Map 每一个元素都是 key-value -->
	<c:forEach items="${sessionScope.cart }" var="entry">
		<h3>商品名称: ${entry.key },数量: ${entry.value }</h3>
	</c:forEach>
</c:if>
</body>
</html>

结果展示:

IE禁用Cookie后的session处理


禁用Cookie后,Session还能否使用?

可以,可以对url进行重写,原理在url;jsessionid=xxx


在程序中可以调用response.encodeURL(url)进行URL重写:

package ustc.lichunchun.servlet.session.demo1;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 向session 保存一个数据
 */
public class WriteSessionServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得Session对象
		// Session对象由服务器创建,开发人员可以调用request对象的getSession方法得到session对象
		// 若request头信息Cookie中没有JSESSIONID,则服务器端创建一个Session对象,并返回给浏览器一个对应的JSESSIONID的cookie
		HttpSession httpSession = request.getSession();
		
		// 向session 保存一个数据
		httpSession.setAttribute("school", "中国科学技术大学");
		
		// 将写回给 浏览器的 JSESSIONID 持久化,否则IE6默认是会话级别cookie
		Cookie cookie = new Cookie("JSESSIONID", httpSession.getId());
		cookie.setMaxAge(60*60);
		cookie.setPath("day07");
		response.addCookie(cookie);
		
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().println("已经向session保存了一个数据!");
		
		String url = "/day07/readsession";
		// 对url 进行重写 拼接 jsessionid -- IE禁用Cookie后的session处理
		url = response.encodeURL(url);
		
		response.getWriter().println("<a href='" + url +"'>查看保存内容</a>");
	}

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

}

结果:


注意

* 如果服务器进行URL重写,所有路径都必须重写(否则,只要有一个没有重写,就找不到Session对象了)

* 不要让用户禁用cookie 

Cookie和Session生命周期分析

Cookie生命周期

Cookie 对象何时创建,何时销毁
创建 : Cookie cookie = new Cookie(name,value) ;  response.addCookie(cookie);
销毁 : 会话cookie会在浏览器关闭时销毁,持久cookie会在cookie过期(MaxAge)后销毁

Session生命周期 

创建:request.getSession() 创建Session 
销毁:三种 1、服务器关闭时销毁 2、session过期时销毁 3、手动调用session.invalidate()

设置session过期时间

1、配置web.xml 
    <!-- 设置session 有效时间,单位是分钟,连续30分钟不使用Session就会销毁 -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
2、调用session对象 setMaxInactiveInterval(int interval) 单位是秒 
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60*60); // 设置session过期时间1小时 

手动调用session.invalidate() 

案例:

清空购物车 --- 完善一下上面的购物车案例,需要修改的是cart.jsp,需要添加的是invalidate.java。

代码:

<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>查看购物车</h1><h3><a href="/day07/session/demo2/invalidate.jsp">清空购物车</a></h3>
<!-- 购物车信息保存 session中 Map<String,Integer> -->
<%
	Map<String, Integer> cart = (Map<String, Integer>)request.getSession().getAttribute("cart");
	if(cart == null){
		out.println("无购物信息");
	}else{
		for(String productName : cart.keySet()){
			out.println("<h3>商品名称:"+productName+" ,数量:"+cart.get(productName)+" </h3>");
		}
	}
%>
<hr/>
<!-- 通过JSTL+EL 编写Map集合 -->
<c:if test="${empty sessionScope.cart }">
	无购物信息
</c:if>
<c:if test="${not empty sessionScope.cart }">
	<!-- 遍历 Map 每一个元素都是 key-value -->
	<c:forEach items="${sessionScope.cart }" var="entry">
		<h3>商品名称: ${entry.key },数量: ${entry.value }</h3>
	</c:forEach>
</c:if>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- 清空购物车 -->
<%
	//销毁Session
	request.getSession().invalidate();
	//request.getRequestDispatcher("/session/demo2/cart.jsp").forward(request, response);
	response.sendRedirect("/day07/session/demo2/cart.jsp");
%>

结果演示:


Session应用

案例:

使用Session完成用户登录

Session经常用来完成系统权限和认证功能

权限和认证的区别:

权限:在用户身份认证后,根据权限知道 --- 你能做什么
认证:用户登陆 --- 你是谁

将登陆用户信息保存到Session 有什么作用 ? ---- 如果session中没有用户信息 则是未登陆

案例:

利用Session完成一次性验证码

* 验证码从session获取后,马上删除 ---- 验证码只能使用一次 

一次性验证码的主要目的就是为了限制人们利用工具软件来暴力猜测密码。 

服务器程序接收到表单数据后,首先判断用户是否填写了正确的验证码,只有该验证码与服务器端保存的验证码匹配时,服务器程序才开始正常的表单处理流程。 密码猜测工具要逐一尝试每个密码的前题条件是先输入正确的验证码,而验证码是一次性有效的,这样基本上就阻断了密码猜测工具的自动地处理过程。 

验证码使用过后,删除相应的session 原因:

作为一个正常用户,我们每访问一次需要填写验证码的页面,生成验证码的脚本都会执行一次,也就说会生成一个新验证码赋值到session里,没有任何问题。但对于一个机器(或一个暴力破解密码脚本),它第一次访问需要填写验证码的页面,然后在session中得到一个验证码,它以后就不用再次访问这个页面了。直接把第一次的数据包更改并再次发送即可,于是,如果没有清除session的网站,每次的验证码都和第一次相同,也就丧失了验证码的本来作用。

原理:


代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	//切换验证码
	function change(){
		document.getElementById("myimg").src="/day07/checkcode?"+new Date().getTime();
	}
</script>
</head>
<body>
<h1>登陆页面</h1>
<h3 style="color:red;">${requestScope.msg }</h3>
<form action="/day07/login" method="post">
	用户名 <input type="text" name="username"/><br/>
	密码 <input type="password" name="password"/><br/>
	请输入验证码 <input type="text" name="checkcode"/><img id="myimg" src="/day07/checkcode" onclick="change()" style="cursor: pointer;" /><br/>
	<input type="submit" value="登陆"/>
</form>
</body>
</html>
package ustc.lichunchun.servlet.session.demo3;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 使用上一篇博客编写代码生成 验证码
 */
public class CheckcodeServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int width = 120;
		int height = 30;
		// 1、创建一张 内存中的缓冲图片
		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		
		// 2、背景色
		Graphics graphics = bufferedImage.getGraphics();// 通过 graphics对象 绘制图片
		// 设置颜色
		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, width, height);
		
		// 3、边框
		graphics.setColor(Color.BLUE);
		graphics.drawRect(0, 0, width-1, height-1);
		
		// 4、写验证码内容
		Graphics2D graphics2d = (Graphics2D)bufferedImage.getGraphics();
		graphics2d.setColor(Color.RED);
		// 设置字体
		//graphics2d.setFont(new Font("Times New Roman", Font.BOLD, 18));
		graphics2d.setFont(new Font("宋体", Font.BOLD, 18));
		//String content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
		String content = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";
		
		// 内容四个字 --- 随机从content中抽取四个字
		Random random = new Random();
		int x = 10;
		int y = 20;
		
		StringBuffer sb = new StringBuffer();
		
		for(int i = 0; i < 4; i++){// 循环四次/五次
			// 为字 生成旋转角度 -30 - 30
			double angle = random.nextInt(60) - 30;
			// 将旋转角度 换算弧度
			double theta = angle/180 * Math.PI;
			
			int index = random.nextInt(content.length());
			char letter = content.charAt(index);// letter 验证码内容
			
			sb.append(letter);
			
			graphics2d.rotate(theta, x, y);
			graphics2d.drawString(letter+"", x, y);
			// 将角度还原
			graphics2d.rotate(-theta, x, y);
			x+=20;
		}
		
		// 将StringBuffer中四个字 转换 String
		String checkcode = sb.toString();
		// 将验证码存入session
		request.getSession().setAttribute("checkcode_session", checkcode);
		
		// 5 绘制随机干扰线
		int x1;
		int x2;
		int y1;
		int y2;
		graphics.setColor(Color.GREEN);
		for(int i = 0; i < 10; i++){
			x1 = random.nextInt(width);
			x2 = random.nextInt(width);
			y1 = random.nextInt(height);
			y2 = random.nextInt(height);
			// 根据两点 绘制直线
			graphics.drawLine(x1, y1, x2, y2);
		}
		
		// 内存中资源 释放
		graphics.dispose();
		
		// 将图片输出到 浏览器 ImageIO
		// 将内存的图片 通过 浏览器输出流 写成 jpg格式图片
		ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
	}

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

}
package ustc.lichunchun.servlet.session.demo3;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 用户登陆
 */
public class LoginServlet extends HttpServlet {
	
	private Map<String, String> userInfo = new HashMap<String, String>();
	@Override
	public void init() throws ServletException {
		// 制作用户假数据
		userInfo.put("aaa", "111");
		userInfo.put("bbb", "222");
		userInfo.put("ccc", "333");
		userInfo.put("ddd", "444");
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// post 乱码解决 --- 验证码为中文数据
		request.setCharacterEncoding("utf-8");
		
		
		// 判断验证码输入是否正确
		String checkcode = request.getParameter("checkcode");
		String checkcode_session = (String) request.getSession().getAttribute("checkcode_session");
		
		// 删除session中验证码 -- 保证一次性
		request.getSession().removeAttribute("checkcode_session");
		
		if(checkcode_session == null || !checkcode.equals(checkcode_session)){
			// 验证码无效 -- 跳回login.jsp
			// response.sendRedirect("/day07/session/demo3/login.jsp");

			// 传递错误信息给jsp
			request.setAttribute("msg", "验证码不正确");
			//此时如果再使用重定向是不对的,因为重定向是另一个request
			request.getRequestDispatcher("/session/demo3/login.jsp").forward(request, response);
			return;
		}
		
		// 1 从请求获得数据
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		// 2 判断用户信息是否正确
		if(userInfo.containsKey(username)){
			// 如果用户名存在
			if(userInfo.get(username).equals(password)){
				// 密码正确 --- 登陆成功
				// 将用户信息 保存session
				request.getSession().setAttribute("username", username);
				
				// 跳转登陆成功 系统主页
				response.sendRedirect("/day07/session/demo3/welcome.jsp");
			}else{
				// 密码错误
				// response.sendRedirect("/day07/session/demo3/login.jsp");
				request.setAttribute("msg", "密码输入错误");
				request.getRequestDispatcher("/session/demo3/login.jsp").forward(request, response);
			}
		}else{
			// 用户名不存在
			// response.sendRedirect("/day07/session/demo3/login.jsp");
			request.setAttribute("msg", "用户名不存在");
			request.getRequestDispatcher("/session/demo3/login.jsp").forward(request, response);
		}
	}

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

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>系统主页</h1>
<%
	//因为session会保存登陆用户信息,如果session中没有该信息 说明用户未登录
	if(request.getSession().getAttribute("username") == null){
		//未登录
		//加这个判断是为了有的人直接输入welcome.jsp这个地址进行访问
		out.println("你还没有登陆,<a href='/day07/session/demo3/login.jsp'>去登陆</a>");
	}else{
		// 已经登陆
		out.println("欢迎你,"+request.getSession().getAttribute("username"));
	}
%>
</body>
</html>

结果演示:


Servlet 三种数据范围

ServletContext
HttpServletRequest
HttpSession 

三种数据范围,每个对象各自维护类似map集合结构,具备相同几个方法

setAttribute 存入一个属性
getAttribute 取出一个属性
removeAttribute 移除一个属性 

三种数据范围对象 在哪些情况使用?

ServletContext 服务器启动时创建,服务器关闭销毁 所有Servlet共享 ---- 保存一些全局数据
例如:数据库连接池、工程配置属性、配置文件内容  ----- 一般不建议使用 

HttpSession 在request.getSession时创建,在三种情况下销毁 ----- 保存与用户相关数据

例如:系统登陆信息、购物车数据 

HttpServletRequest 在客户端发起请求时,服务器创建对象,在响应结束时 对象销毁 ----- 保存Servlet向JSP传输数据信息

例如:执行某个操作,Servlet将操作结果传递JSP (Servlet将登陆错误信息传递JSP )、Servlet将数据库查询结果传递JSP 

以上三种数据范围 ServletContext > HttpSession > HttpServletRequest 

* 宗旨 优先使用生命周期短的 

Servlet系列三篇博客--总结

博客一

1、编写一个Servlet --- HelloWorld     response.getWriter().print()
2、设置response编码集,向浏览器输入中文信息  response.setContentType("text/html;charset=utf-8");
3、将九九乘法表打印浏览器页面 ----- 添加for循环 
4、编写页面让用户输入一个数字,在Servlet根据用户输入数字 打印乘法表 
5、用户输入一段字母内容,在浏览器上输入 每个字符出现几次 
6、网站访问次数 (选做)
7、读取web工程中一个文件 (getServletContext().getRealPath())
理论:
1、Servlet生命周期
2、ServletConfig和ServletContext 
3、url-pattern 三种写法

博客二: 

1、重定向 ---- response.setStatus  response.setHeader
2、自动跳转 ---- refresh
3、禁用缓存 ---- 三个头信息 
4、文件下载 (复杂值得做)
5、验证码程序 整理一下 (不用重写)
6、获得当前访问资源路径 request.getRequestURI().substring(request.getContextPath().length());
7、获得客户端 IP request.getRemoteAddr()
8、防盗链 request.getHeader(referer)
9、获得请求参数 乱码问题 post get 乱码解决 (博客二重点**** )
理论:
1、200、302 、304 、404 、500 意思
2、refrer refresh Content-Type Content-Disposition 禁止缓存三个头 ----- 含义
3、get和post请求方式区别
4、乱码发生原因 (掌握)

博客三

1、记录上次访问时间  cookie
2、商品浏览记录 cookie
3、商品购物车 session
4、登陆一次性验证码 session 
理论:
1、cookie和session区别
2、会话cookie 和持久cookie
3、第一方cookie和第三方cookie
4、关闭浏览器是否清除cookie ?
5、持久cookie删除
6、关闭浏览器,重新打开浏览器session还能继续使用 ?原理 ?
7、浏览器禁用cookie,session还能否使用
8、session销毁三种情况
9、一次性验证码原理
10、Servlet三种数据范围区别

猜你喜欢

转载自blog.csdn.net/zhongkelee/article/details/52420034