day_1_12 JavaWeb系列学习总结之cookie&session

cookie&session都是会话跟踪技术.

Cookie: 是由服务器创建, 然后通过响应头发送给浏览器, 并且保存在浏览器中, 当浏览器再次访问服务器的时候, 会将Cookie放在请求头中传给服务器.

在浏览器与服务器中间的执行过程:
Cookie.png

在服务器中如何创建一个Cookie?

Cookie cookie = new Cookie(name, value);
示例:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 创建一个cookie对象
        Cookie cookie = new Cookie("name", "gouwa");
        // 设置Cookie响应头
        response.addCookie(cookie);
    }
cookie中保存中文

默认情况下, value不能是中文
但是可以通过URL编码, 在Cookie中保存中文!

     //编码: URLEncoder
    static String encode(String s, "utf-8")
     //解码: URLDecoder
     static String decode(String s, "utf-8")

示例代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // post请求乱码处理
        request.setCharacterEncoding("utf-8");

        // 获取用户名并且保存到Cookie中
        String username = request.getParameter("username");
        // 编码
        username = URLEncoder.encode(username, "utf-8");

        Cookie cookie = new Cookie("username", username);
        // 设置cookie保存1小时
        cookie.setMaxAge(60 * 60);
        response.addCookie(cookie);
    }

通过response将cookie设置到响应头

    // 常用
    void addCookie(Cookie cookie)
    void setHeader(String name, String value)

响应头:
Set-Cookie:name=gouwa
请求头:

        Cookie:
        JSESSIONID=7AFE4B9766B503964702B0CC7C9C14DE; name=gouwa; ASP.NET_SessionId=2y0jnu5yxbqk0j20luqzca2z;
        ticket=f92223d3477d4a759e195fd41f4e5c6e; Idea-755a90e2=cc8656ab-7ff4-4417-9c64-dd3911e79468;

JSESSIONID=C476C4B2FF9BD2D9572E5F84708A9634
而Session底层是怎样来依赖Cookie的?
sessionid -> JSESSIONID

在服务器中获取浏览器传递过来的Cookie
    // 通过request对象获取
    Cookie[] getCookies()

cookie的示例:
要求: 在登录页面登录一次以后, 可以将用户名保存到登录框中,
第二次登录的时候还有用户名, 用户名不要使用中文!
思路:
1. 表单提交到servlet, 获取到用户名, 将用户名保存到Cookie中,
然后通过响应头发送给浏览器
2. 当再次访问登录的jsp页面时, 将Cookie取出来, 并且显示在用户名的输入框中
实现代码: login.jsp和LoginServlet.java

<%@ page import="java.net.URLDecoder" %>
<%--
  User: menglanyingfei
  Date: 2018/1/12
  Time: 10:13
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>登录</title>
</head>
<body>
    <%-- 获取浏览器发送过来的Cookie
    --%>
    <%
        String value = "";
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // 判断Cookie的名称是否等于"username"
                if ("username".equals(cookie.getName())) {
                    value = cookie.getValue();
                    // 解码
                    value = URLDecoder.decode(value, "utf-8");
                }
            }
        }
    %>
    <form action="/day_1_12/loginServlet" method="post">

        用户名:<input type="text" name="username" value="<%= value%>">
        <br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

Servlet处理逻辑:

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * Created by menglanyingfei on 2018/1/12.
 */
@WebServlet(name = "LoginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 请求乱码
        request.setCharacterEncoding("utf-8");

        // 获取用户名并且保存到Cookie中
        String username = request.getParameter("username");
        // 编码
        username = URLEncoder.encode(username, "utf-8");

        Cookie cookie = new Cookie("username", username);

        cookie.setMaxAge(60 * 60);
        response.addCookie(cookie);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
设置Cookie的存活时间

cookie默认当浏览器关闭的时候, 会清除掉.

        setMaxAge(int expiry)
        setMaxAge(1), 以秒为单位, 1小时 = 60 * 60
            表示cookie会保存到本地硬盘中, 关闭浏览器不会消失
        setMaxAge(-1)
            默认情况
        setMaxAge(0)
            表示立即清除cookie
路径问题
  1. 查看路径
    浏览器查看cookie
    cookie.getPath()

  2. cookie路径的特点:
    比如cookie的路径
    /day_1_12/servlet
    第二次访问服务器的路径:
    /day_1_12/CookiePathDemo2
    那么第二次访问访问浏览器, 不会将cookie带给服务器

只有当访问路径包含了Cookie的路径的时候, 浏览器才会将cookie带给服务器

小案例:
获取上次访问的时间
注意:Cookie的value里不能设置非法字符, 如空格
cookie不能跨浏览器.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // 获取上次访问的时间
        String message = "你是第一次访问该网站";
        Date date = new Date();

//        String time = date.toLocaleString();
        String time = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(date);
        Cookie c = new Cookie("time", time);
        c.setMaxAge(60 * 60);
        response.addCookie(c);

        // 获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("time".equals(cookie.getName())) {
                    message = "您上次访问该网站的时间是" + cookie.getValue();
                }
            }

        }

        response.getWriter().print(message);
    }

session

HttpSession(非常重要)
什么叫做一次会话?
其中, 包括多次请求. 我们可以理解为打开浏览器, 关闭浏览器看成是一次会话.
一个session对象对应一次会话, 在这个过程中有很多request对象,
但是只有一个session对象.

session依赖cookie保存sessionid:
session依赖cookie保存sessionid.png
HttpSession是一个域对象, 所以肯定有这三个方法:

        setAttribute(name, value)  保存数据
        getAttribute(name)  获取数据
        removeAttribute(name)  删除数据

现在对比三大域对象:
范围:
最大的ServletContext: application
对应于整个项目, 它随着服务器的开启就创建, 服务器关闭就销毁

HttpSession: session
一个session对象伴随着一次会话, 只要浏览器不关闭或者没有超过session最大存活时间, session对象就一直存在.
HttpServletRequest: request
一个request对象对应一次请求, 只有在转发的时候, 才能使用
request作为域对象传输数据

获取session对象
  1. 在jsp页面中, session对象不需要获取, 直接使用即可
  2. 在servlet中, 使用request对象获取
HttpSession session = request.getSession()
HttpSession session = request.getSession(boolean create);

如果create 为true, 那么和不带参数是一样的, 如果没有当前会话并且 create 为 true,则返回一个新会话。
如果b为false, 那么有session就直接获取, 没有session就返回null.

常用API以及配置session存活时间
    getId():  获取session的id号
    long getCreationTime() :
        获取session的创建时间返回一个当前时间的毫秒值
    getLastAccessedTime()
        获取最后的活动时间

     (***)
     int getMaxInactiveInterval()
    获取session的最大不活动时间
      void invalidate()
      销毁session, 一般用来做退出按钮

      setMaxInactiveInterval(int interval)
      设置session的最大不活动时间, 还可以在web.xml文件中
      配置最大不活动时间

       <!--配置session最大不活动时间, 以分钟为单位 -->
         <session-config>
               <session-timeout>60</session-timeout>
         </session-config>
完整代码地址

https://github.com/menglanyingfei/Java/tree/master/JavaWebTrain

JavaWeb应用中,为了实现用户登录认证,通常会使用SessionCookieSession是在服务端保存用户状态的一种机制,每个用户在访问服务器时都会被分配一个唯一的Session ID,通过该ID可以在服务端存储和获取与该用户相关的信息。在用户登录后,可以将用户信息存储到Session中,供之后的页面访问和使用。 Cookie是在客户端保存用户状态的一种机制,通过在服务端设置Cookie,在客户端保存一个唯一的标识符,带着该标识符可以在客户端和服务端之间传递数据。在用户登录后,可以将用户信息存储到Cookie中,供之后的页面访问和使用。 使用SessionCookie实现登录认证的基本流程如下: 1. 用户在登录页面输入用户名和密码。 2. 服务器接收到请求后,验证用户名和密码是否正确。 3. 如果验证通过,生成一个唯一的Session ID,并将用户信息存储到Session中。 4. 将Session ID 存储到Cookie中,并设置Cookie的有效期。 5. 用户访问其他页面时,将Cookie中的Session ID 发送到服务器,服务器根据Session ID 获取用户信息,判断用户是否登录。 6. 如果用户已经登录,返回需要访问的页面内容;如果用户未登录,跳转到登录页面。 示例代码如下: ```java // 生成Session ID String sessionId = UUID.randomUUID().toString(); // 将用户信息存储到Session中 HttpSession session = request.getSession(); session.setAttribute("username", username); // 将Session ID 存储到Cookie中,并设置有效期为1天 Cookie cookie = new Cookie("sessionId", sessionId); cookie.setMaxAge(24 * 60 * 60); response.addCookie(cookie); // 获取Cookie中的Session ID,并根据Session ID 获取用户信息 Cookie[] cookies = request.getCookies(); String sessionId = null; if (cookies != null) { for (Cookie c : cookies) { if ("sessionId".equals(c.getName())) { sessionId = c.getValue(); break; } } } if (sessionId != null) { HttpSession session = request.getSession(false); if (session != null) { String username = (String) session.getAttribute("username"); if (username != null) { // 用户已经登录,返回需要访问的页面内容 } } } // 用户未登录,跳转到登录页面 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值