JavaWeb (十一) Cookie 和 Session

1、Cookie 饼干

1.1 什么是 Cookie 

Cookie翻译过来是饼干。
Cookie是由服务器通知客户端,保存键值对的一种技术。
Cookie保存到客户端,然后每次发起请求的时候,浏览器会把cookie信息发送给服务器。
每个Cookie的大小不能超过4kb

1.2 如何创建Cookie

  1. 服务器new一个Cookie对象
  2. 调用response.addCookie(cookie); 通知客户端保存cookie

        protected void createCookie(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 1、服务器new一个Cookie对象
		Cookie cookie = new Cookie("aaa", "aaaValue");// 在服务器内存中
		Cookie cookie2 = new Cookie("bbb", "bbbValue");// 在服务器内存中
		// 2、调用response.addCookie(cookie); 通知客户端保存cookie
		response.addCookie(cookie2);
		response.addCookie(cookie);
		response.getWriter().write("Cookie已经创建成功");
	}

谷歌浏览器查看Cookie

火狐查看Cookie

1.3 如何获取Cookie

Cookie的工具类

public class CookieUtil {

	public static Cookie findCookie(String name, Cookie[] cookies) {
		if (name == null || cookies == null || cookies.length == 0) {
			return null;
		}
		for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) {
				return cookie;
			}
		}
		return null;
	}
}

获取Cookie的代码:

    protected void getCookie(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
		// 得到全部的cookie(客户端传递的cookie)
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies) {
			response.getWriter().write(
					"服务器收到Cookie[" + cookie.getName() + "] ,值:"
							+ cookie.getValue() + "<br/>");
		}
//		Cookie iWantCookie = null;//想要aaa的cookie
//		for (Cookie cookie : cookies) {
//			if ("aaa".equals(cookie.getName())) {
//				iWantCookie = cookie;
//				break;
//			}
//		}
		Cookie iWantCookie = CookieUtil.findCookie("bbbcc", cookies);
		// 说明找到了Cookie
		if (iWantCookie != null) {
			response.getWriter().write("我找到了我需要的Cookie===>>>" + iWantCookie);
		}
	}

1.4 Cookie值的改修改

方法一:

  1. 直接new一个需要修改的同名的Cookie。
  2. 在new的时候,直接把新的值传递到构造器中。
  3. 调用response.addCookie(cookie);
//		1、直接new一个需要修改的同名的Cookie。
//		2、在new的时候,直接把新的值传递到构造器中。
		Cookie cookie = new Cookie("aaa", "newAaaValue");
//		3、调用response.addCookie(cookie);
		response.addCookie(cookie);

方法二:

  1. 在服务器端,先查找到你要修改的Cookie。
  2. 调用setValue方法(设置新的值)不支持中文
  3. 调用response.addCookie()
//		1、在服务器端,先查找到你要修改的Cookie。
		Cookie iWantCookie = CookieUtil.findCookie("bbb", request.getCookies());
		if (iWantCookie != null) {
	//		2、调用setValue方法(设置新的值)不支持中文
			iWantCookie.setValue("newBbbValue");
	//		3、调用response.addCookie()
			response.addCookie(iWantCookie);
			response.getWriter().write("bbb的Cookie已经被改了。你再去看一下");
		}

1.5 Cookie 生命控制

setMaxAge()        设置Cookie的存活时间。以秒为单位
    正数            表示在指定的秒数后期
    负数            表示Cookie不会被保存起来。浏览器一关就被删除(默认)
    零                表示立即删除Cookie

马上删除Cookie

    protected void deleteNow(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Cookie iWantCookie = CookieUtil.findCookie("aaa", request.getCookies());
		if (iWantCookie != null) {
			iWantCookie.setMaxAge(0);// 设置为零,表示收到响应后,就马上删除Cookie
			response.addCookie(iWantCookie);
			response.getWriter().write("很不幸,aaa的Cookie被辞退了!");
		}
	}

让Cookie活一个小时

        protected void life3600(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Cookie iWantCookie = CookieUtil.findCookie("bbb", request.getCookies());
		if (iWantCookie != null) {
			iWantCookie.setMaxAge(60*60);//表示Cookie一个小时后过期
			response.addCookie(iWantCookie);
			response.getWriter().write("很幸运,bbb的生活又延长了!");
		}
	}

1.6 Cookie有效路径Path的设置

path属性可以有效的过滤cookie是否发送给服务器。

现在Cookie都会只在一请求,就会全部发送给服务器。就会产生流量浪费。

Cookie默认的path值是 /工程名

path=/day14            那么,只要请求的地址是http://ip:port/day14/*            都会发送给服务器。    

path/day14/abc        那么,只请求的地址是http://ip:port/day14/abc/*        才会发送给服务器。


        CookieA        path=/day14
        CookieB        path=/day14/abc

(1)请求地址是:    
        http://ip:port/day14                                   CookieA会发送给服务器。

        http://ip:port/day14/abc/a.html                CookieA和CookieB都会发送给服务器

(2)path的设置:

        protected void setPath(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Cookie cookie = new Cookie("path1", "path1Value");
		cookie.setPath(request.getContextPath() + "/abc");// path=/day14/abc
		response.addCookie(cookie);
		response.getWriter().write("有path的Cookie我创建好了!");
	}

1.7 Cookie 联系——面输入登录用户名

表单:

    <form action="loginServlet" method="post">
			用户名:<input type="text" name="username" value="${ cookie.username.value }"/><br/>
			密码:<input type="password" name="password" value=""/><br/>
			<input type="submit" />
		</form>

LoginServlet程序

        protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 获取请求参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		if ("admin".equals(username)&&"123456".equals(password)) {
			//登录成功
			Cookie cookie = new Cookie("username", username);
			cookie.setMaxAge(60*60*24);// 一天
			response.addCookie(cookie);
			System.out.println("登录成功!");
		} else {
			System.out.println("登录失败!");
		}
		
	}

2、Session

2.1 什么是 Session 会话?

Session接口,是域对象
Session服务器用来维护和标识客户端之间联系的一种技术。
我们经常用Session来保存用户的数据。

2.2 如何创建Session 和 获取 (id 号,是否为新)

       request.getSession()        
            第一次调用创建Session并返回
           之后调用,是返回之前创建好的。

      isNew      判断是否是新创建出来的
      getId()    获取会话的唯一标识

        protected void createOrGetSession(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 创建或获取Session对象
		HttpSession session = request.getSession();
		response.getWriter().write("会话的id是:" + session.getId() + "<br/>");
		response.getWriter().write("会话是否是新的:" + session.isNew() + "<br/>");
	}

2.3 Session 域数据的存取

        protected void setAttribute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 保存aa数据
		request.getSession().setAttribute("aa", "aaValue");
		response.getWriter().write("往Session中保存到aa=aaValue");
	}

	protected void getAttribute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().write(
				"Session中的域数据aa值是:" + request.getSession().getAttribute("aa"));
	}

2.4 Session 声明周期控制

Session的默认的超时时间为30分钟。因为Tomcat服务器的配置文件。web.xml早已有配置

  <!-- ==================== Default Session Configuration ================= -->
  <!-- You can set the default session timeout (in minutes) for all newly   -->
  <!-- created sessions by modifying the value below.                       -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

以上Tomcat服务器web.xml配置文件的配置对所有运行在此tomcat服务器上的所有web工程,默认创建出来的Session都有效。

运行在tomcat服务器上的web工程,所有创建出来的Session的默认超时时间为30分钟。

如果希望自己的web工程所有的Session超时不按照Tomcat默认。我们可以在自己的web工程的web.xml配置文件中做以上相同的配置

	<!-- 表示你的web工程,Session的超时时间为20分钟 -->
	<session-config>
		<session-timeout>20</session-timeout>
	</session-config>

设置单个Session的超时

setMaxInactiveInterval()        设置单个的Session的超时时间
getMaxInactiveInterval();        获取Session的超时时间

       

        protected void lifeThree(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 获取Session
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(3);//将当前的Session设置为3秒超时
		response.getWriter().write("当前会话3秒后失效!");
	}

   invalidate()    让此会话失效(马上清掉他)

	protected void deleteNow(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();
		response.getWriter().write("当前会话,已无效!");
	}

2.5 浏览器和Session 之间关联的技术内幕

发布了222 篇原创文章 · 获赞 60 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_42405670/article/details/103931568
今日推荐