Session 和 Cookie 使用

目录

一、Cookie

1、Cookie的创建

  2、服务器获取Cookie

3、Cookie值的修改

方案一

方案二

4、浏览器查看Cookie

5、Cookie生命控制

 6、Cookie有效路径Path的设置

 7、Cookie免输入用户名登录

二、Session

1、Session

2、创建Session和获取

3、Session域数据的存取

4、Session生命周期控制

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


一、Cookie

Cookie  是服务器通知客户端保存键值对的一种技术。客户端有了  Cookie  后,每次请求都发送给服务器。每个  Cookie  的大小不能超过  4kb

1、Cookie的创建

使用BaseServlet抽取Servlet对象,在请求中携带名称为action,值为方法名的参数动态调用请求方法。

public abstract class BaseServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //解决请求中文乱码问题
       req.setCharacterEncoding("UTF-8");
       //解决响应中文乱码问题
        resp.setContentType("text/html; charset=UTF-8");

        //获取参数action的值
        String action=req.getParameter("action");

        try {
            // 匹配指定名称和参数的类的方法,此方法返回的是Method对象
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            //调用目标业务方法,这里的 this 是子类
            method.invoke(this,req,resp);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

Servlet程序 

public class CookieServlet extends BaseServlet {
    protected void createCookie(HttpServletRequestreq,HttpServletResponse resp)throwsServletException, IOException {
        //1 创建  Cookie对象
        Cookie cookie = new Cookie("key4", "value4"); 

        //2 通知客户端保存  Cookie
        resp.addCookie(cookie);

        resp.getWriter().write("Cookie创建成功");
    }    
}

web.xml

    <servlet>
        <servlet-name>CookieServlet</servlet-name>
        <servlet-class>com.servlet.CookieServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CookieServlet</servlet-name>
        <url-pattern>/cookieServlet</url-pattern>
    </servlet-mapping>

请求地址:localhost:8080/13_cookie_session/cookieServlet?action=createCookie

 解释:当请求到达CookieServlet,由于没有 doGet() 方法,会向父类寻找, BaseServlet中有 doGet()方法,调用父类的 doGet()方法,首先获取 action 的值createCoookie,这里的 this是子类,通过反射调用子类名为 createCookie 的方法。

  2、服务器获取Cookie

 Cookie的工具类:查找指定名称的  Cookie对象

public class CookieUtils {
    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;
    }
}
    protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Cookie[] cookies = req.getCookies();

        for (Cookie cookie : cookies) {
            resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
        }

        Cookie iWantCookie = CookieUtils.findCookie("key3", cookies);
        if (iWantCookie != null) {
            resp.getWriter().write("找到了需要的Cookie");
        }
    }

3、Cookie值的修改

方案一

    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletExcepton, IOException {
         Cookie cookie = new Cookie("key3","NewValue");
         resp.addCookie(cookie);
    }

方案二

    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie1 = CookieUtils.findCookie("key3", req.getCookies());
        if(cookie1!=null){
            cookie1.setValue("newValue2");
            resp.addCookie(cookie1);
        }
    }

4、浏览器查看Cookie

5、Cookie生命控制

Cookie  的生命控制指的是如何管理  Cookie  什么时候被销毁(删除) 

setMaxAge()

  • 正数,表示在指定的秒数后过期
  • 负数,表示浏览器一关,Cookie  就会被删除(默认值是-1) 
  • 零,表示马上删除  Cookie
    protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Cookie cookie = new Cookie("life3600", "life3600");
        cookie.setMaxAge(60 * 60);
        resp.addCookie(cookie);
        resp.getWriter().write("已经创建了一个存活一小时的 Cookie");
    }

    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = CookieUtils.findCookie("key3", req.getCookies());

        if(cookie!=null){
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
            resp.getWriter().write("key3已删除");
        }
    }

    protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Cookie cookie = new Cookie("defalutLife","defaultLife");
        cookie.setMaxAge(-1);//设置存活时间
        resp.addCookie(cookie);
        resp.getWriter().write("默认的会话级别的Cookie");
    }

cookie.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie</title>
	<base href="http://localhost:8080/13_cookie_session/">
<style type="text/css">

	ul li {
		list-style: none;
	}
	
</style>
</head>
<body>
	<iframe name="target" width="500" height="500" style="float: left;"></iframe>
	<div style="float: left;">
		<ul>
			<li><a href="cookieServlet?action=createCookie" target="target">Cookie的创建</a></li>
			<li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取</a></li>
			<li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a></li>
			<li>Cookie的存活周期</li>
			<li>
				<ul>
					<li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默认存活时间(会话)</a></li>
					<li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除</a></li>
					<li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小时)</a></li>
				</ul>
			</li>
			<li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置</a></li>
			<li><a href="" target="target">Cookie的用户免登录练习</a></li>
		</ul>
	</div>
</body>
</html>

 6、Cookie有效路径Path的设置

Cookie 的 path 属性可以有效的过滤哪些 Cookie 可以发送给服务器。哪些不发。 

path 属性是通过请求的地址来进行有效的过滤。

  • CookieA     path=/工程路径 
  • CookieB     path=/工程路径/abc

请求地址如下:

http://ip:port/工程路径/a.html

  • CookieA   发送 
  • CookieB   不发送

http://ip:port/工程路径/abc/a.html

  • CookieA 发送 
  • CookieB 发送
    protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie = new Cookie("path1", "path1");
        // getContextPath() 得到工程路径
        cookie.setPath( req.getContextPath() + "/abc" ); 

        //访问http://localhost:8080/13_cookie_session/abc才能看到该cookie
        resp.addCookie(cookie);

        resp.getWriter().write("创建了一个带有 Path 路径的 Cookie");
    }

 7、Cookie免输入用户名登录

 login.jsp 页面

<form action="http://localhost:8080/13_cookie_session/loginServlet" method="get"> 
    用户名:<input type="text" name="username" value="${cookie.username.value}"> <br> 
    密码:<input type="password" name="password"> <br>
    <input type="submit" value="登录"> 
</form>

LoginServlet 程序

public class LoginServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if("1".equals(username)&&"1".equals(password)){
            Cookie cookie = new Cookie("username", username);
            cookie.setMaxAge(60*60*24); //当前cookie一天有效
            resp.addCookie(cookie);
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
    }
}

二、Session

1、Session

  1. Session 是一个接口(HttpSession)
  2. Session  就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
  3. 每个客户端都有自己的一个  Session  会话。
  4. Session  会话中,我们经常用来保存用户登录之后的信息。

2、创建Session和获取

request.getSession()

  • 第一次调用是:创建  Session  会话
  • 之后调用都是:获取前面创建好的  Session  会话对象。 

isNew():判断到底是不是刚创建出来的(新的)

  • true    表示刚创建
  • false     表示获取之前创建

每个会话都有一个身份证号。也就是  ID 值。而且这个  ID  是唯一的。 

  • getId()  得到Session  的会话 id 值。
    protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();

        boolean isNew = session.isNew();

        String id = session.getId();

        resp.getWriter().write("得到的session的id是:"+id+"<br/>");
        resp.getWriter().write("session是否是新创建的"+isNew+"<br/>");
    }

3、Session域数据的存取

public class SessionServlet extends BaseServlet{
    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().setAttribute("key1", "value1");
        resp.getWriter().write("已经往 Session 中保存了数据");
    }

    protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object attribute = req.getSession().getAttribute("key1");
        resp.getWriter().write("从 Session 中获取出 key1 的数据是:" + attribute);
    }
}

4、Session生命周期控制

/*
    设置Session的超时时间(以秒为单位),超过指定的时长,Session 就会被销毁。
        值为正数的时候,设定 Sessio 的超时时长。 
        负数表示永不超时
*/
public void setMaxInactiveInterval(int interval)   

//获取 Session 的超时时间 
public int getMaxInactiveInterval() 

//让当前 Session 会话马上超时无效。
public void invalidate()      

Session  默认的超时时间长为  30  分钟。

因为在 Tomcat 服务器的配置文件 web.xml 中默认有以下的配置,它就表示配置了当前 Tomcat 服务器下所有的 Session 超时配置默认时长为:30  分钟。

<session-config>
    <session-timeout>30</session-timeout> 
</session-config>

如果说。你希望你的  web  工程,默认的  Session  的超时时长为其他时长。你可以在你自己的  web.xml  配置文件中做以上相同的配置。就可以修改你的 web 工程所有  Seession  的默认超时时长。

<!--表示当前  web工程。创建出来    的所有  Session默认是  20分钟    超时时长--> 
<session-config>
    <session-timeout>20</session-timeout> 
</session-config>

如果你想只修改个别  Session  的超时时长。就可以使用上面的  API。

Session超时的概念介绍

 

    protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.invalidate();
        resp.getWriter().write("Session 已经设置为超时(无效)");
    }

    protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        session.setMaxInactiveInterval(3);
        resp.getWriter().write("当前 Session 已经设置为 3 秒后超时");
    }

session.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session</title>
	<base href="http://localhost:8080/13_cookie_session/">
<style type="text/css">

	ul li {
		list-style: none;
	}
	
</style>
</head>
<body>
	<iframe name="target" width="500" height="500" style="float: left;"></iframe>
	<div style="float: left;">
		<ul>
			<li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)</a></li>
			<li><a href="sessionServlet?action=setAttribute" target="target">Session域数据的存储</a></li>
			<li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a></li>
			<li>Session的存活</li>
			<li>
				<ul>
					<li><a href="sessionServlet?action=defaultLife" target="target">Session的默认超时及配置</a></li>
					<li><a href="sessionServlet?action=life3" target="target">Session3秒超时销毁</a></li>
					<li><a href="sessionServlet?action=deleteNow" target="target">Session马上销毁</a></li>
				</ul>
			</li>
			<li><a href="" target="target">浏览器和Session绑定的原理</a></li>
		</ul>
	</div>
</body>
</html>

 

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

Session  技术,底层其实是基于  Cookie  技术来实现的。

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鲁蛋儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值