web複習day05:cookie和session

回顧:

響應: HttpServletResponse

行: 協議/版本 狀態碼(說明)

    200

    302(location)

    304

    404

    500

    setStatus();

    sendError();

頭:  key/values

    setHeader("頭名稱","值");

        重定向:

            設置狀態碼 302

            location

        sendRedirect("重定向的路徑");

        refresh

        content-type

        content-disposition

            設置兩個頭,一個流

體: 需要瀏覽器解析的內容

    getWriter(); 

    getOutputStream();

會話技術

會話概述:

會話: 一次通話.(不標準)

作用: 用來保存瀏覽器在訪問服務器的過程中 產生的數據

Cookie:

概述:

英文直譯:餅乾; 小甜點

瀏覽器端的會話技術

作用:

將會話中產生的數據存放在瀏覽器端

==小結:== 

cookie存在瀏覽器上

cookie由服務器創建

cookie中存放的數據不安全

cookie中存到的數據量不超過4kb

cookie中存放的是文本信息(String)

工作流程

瀏覽器訪問服務器時,服務器生成cookie(鍵值對形式),通過響應(響應頭 set-cookie)返回給瀏覽器,cookie保存在瀏覽器上.

下次訪問服務器的時候,根據一定的規則攜帶不同的cookie

將cookie裝在請求頭中帶到服務器上   cookie頭

==有關Cookie的API==

創建cookie

new Cookie(String name,String value);

返回給瀏覽器

response.addCookie(Cookie c);

意思爲:給set-Cookie設置值

設置Cookie在瀏覽器的存活時間

注意:  cookie的默認存活時間爲瀏覽器會話結束時(瀏覽器關閉)

setMaxAge(int 秒數);

如果秒數=0:刪除該cookie(前提:路徑必須相同)

設置路徑

setPath(String cookie的路徑);

默認路徑:

    /day05/hello_cookie

    /day05

注意: 一旦給cookie設置了綁定路徑,那麼默認的綁定路徑就會被覆蓋.

測試cookie的默認綁定路徑:
訪問路徑:  /day05/createCookie
名稱      值       綁定路徑
akey     47         /day05
bkey     bvalue     /day05
訪問路徑:  /day05/setMaxAge
ckey     cvalue     /day05
訪問路徑:  /day05/aa/defaultPath
aakey    aavalue    /day05/aa/
bbkey    bbvalue    /day05/aa
結論: cookie的默認綁定路徑爲訪問路徑的上一層

獲取請求中的所有cookie

request.getCookies();  數組接收 cookie[]

==// 瀏覽器攜帶cookie的規則==

 訪問路徑字符串包含原則

//訪問路徑 /day05/createCookie      (/day05   /day05/createCookie)
//  名稱          值           綁定路徑    
    akey        47              /day05
    bkey        bvalue          /day05
    ckey        cvalue          /day05
//訪問路徑 /day05/setMaxAge         (/day05   /day05/setMaxAge)
    akey        47              /day05
    bkey        bvalue          /day05
    ckey        cvalue          /day05
//訪問路徑 /day05/aa/defaultPath    (/day05   /day05/aa   /day05/aa/defaultPath)
    akey        47              /day05
    bkey        bvalue          /day05
    ckey        cvalue          /day05
    aakey       aavalue         /day05/aa
    bbkey       bbvalue         /day05/aa
    cbkey       ccvalue         /day05/aa

獲取Cookie的名稱

getName();

獲取Cookie的值

getValue();

注意事項

cookie不能跨瀏覽器

cookie中存放的內容不能超過 4 kb

cookie中存放的是文本信息

通過服務器刪除指定cookie對象:

將cookie的存活時間設置爲 0 秒

創建相同名稱 和 相同路徑的cookie,將其覆蓋

Session:

概述:

英文直譯:開會,會議

服務器端的會話技術

作用:

在服務器上存放一次會話中的數據

==小結:== 

session存在服務器上

session由服務器創建

session中存放的數據相對安全

session中存放的數據量不受限制

session中可以存放一切數據(object)

工作流程

瀏覽器訪問服務器時,服務器會獲取瀏覽器的數據,判斷瀏覽器是否攜帶了sessionID

如果沒帶:

    如果沒帶,且想使用session,需要先創建session(服務器端的內存空間,由服務器創建),這樣以來就可以使用這個session了,使用完畢後將sessionID返回給瀏覽器,由瀏覽器保存sessionID(依賴Cookie)

如果帶了:

    如果帶了,服務器要先獲取sessionID,根據sessionID找到這個session

    沒找到:

        想使用session,需要先創建session(服務器端的內存空間,由服務器創建),這樣以來就可以使用這個session了,使用完畢後將sessionID返回給瀏覽器,由瀏覽器保存sessionID(依賴Cookie)

    找到直接操作session

關於Session的API

獲取一個session:

在java中我們認爲第一次調用request.getSession()就是創建session空間

HttpSession session = request.getSession();

    創建session空間

    自動根據jsessionid找到session空間

Session的屬性操作

setAttrbute(String name,object obj);

getAttrbute(name);

removeAttribute(String name);  

Session生命週期

創建:

java代碼中第一次調用request.getSession()

不攜帶jsessionid也會創建

攜帶jsessionid但找不到對應的session也會創建

銷燬:

服務器非正常關閉

session超時:tomcat默認超時時間爲30分種

手動銷燬:調用session.invalidate()方法

域對象(Servlet中的三大域對象)

ServletContext: 上下文對象

生命週期

    創建:服務器啓動的時候,會爲每一個項目創建一個servletContext對象

    銷燬:服務器關閉的時候 或 項目從服務器上移出

    作用範圍:整個項目

    作用:

        獲取文件mime類型

        獲取資源在服務器上的完整路徑

        存放共享的數據

HttpSession: 會話

生命週期

    創建:調用request.getSession()時

    銷燬:

        服務器非正常關閉

        Session超時

        手動銷燬

            調用invalidate方法

    作用範圍:一次會話

    作用:存放私有的數據

Request:請求

生命週期

    創建:請求來的時候

    銷燬:響應生成的時候

作用範圍:一次請求鏈中

作用:存放一次請求串中的數據

案例:

案例1-記錄上次訪問時間

需求分析:
    訪問servlet記錄訪問時間
    如果用戶是第一次訪問該servlet,那麼返回: "您是第一次訪問,歡迎再來玩兒呀..."
    如果用戶不是第一次訪問則返回上一次訪問的時間"...."
技術分析:
    cookie
步驟分析:

有一個數組 str = ["小張","小李","小王吧"....] 從該數組中查找是否有"小王吧".
    for(String value:str){
        if("小王吧".equals(value)){
            // 輸出結果
            // 經理讓這麼寫的,目的是讓用戶二次付費進行優化
            //break;
        }
    }

案例2-用戶登錄(驗證碼)

需求分析:
    帶有驗證碼的用戶登錄.
技術分析:
    驗證碼:
        訪問登錄頁面時需要生成驗證碼圖片,並將生成的驗證碼保存到session中
    登錄:
        用戶名 密碼 驗證碼
        // 首先校驗驗證碼
        //1.獲取session中生成的驗證碼
        //2.獲取用戶輸入的驗證碼
        //3.校驗....
        // 如果校驗不通過,return
        // 通過後,執行登錄

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<body>
    <h1>我是首頁</h1>
    <form action="login" method="post">
        用戶名: <input type="text" name="username"> <br>
        密碼: <input type="password" name="password"> <br>
        驗證碼: <input type="text" name="ucode"> <img src="code" alt=""> <br>
        <input type="submit" value="登錄">
    </form>

</body>
</html>

domain

package com.itheima.domain;

public class User {
    private int id;
    private String username;
    private String password;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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;
    }
}

dao

package com.itheima.dao;

import com.itheima.domain.User;
import com.itheima.utils.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

public class UserDao {
    // 登錄
    public User login(User user) {
        try {
            JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
            String sql = "select * from user where username = ? and password = ? ";
            return template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),
                    user.getUsername(),user.getPassword());
        } catch (DataAccessException e) {
            return null;
        }
    }
}

service

package com.itheima.service;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;

public class UserService {

    public User login(User user) {
        UserDao dao = new UserDao();
        return dao.login(user);
    }
}

utils

package com.itheima.utils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "CodeServlet",urlPatterns = "/code")
public class CodeServlet extends HttpServlet {

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

        // 使用java圖形界面技術繪製一張圖片

        int charNum = 4; // 生成4位的驗證碼
        int width = 20 * 4; // 圖片寬
        int height = 28; // 圖片高

        // 1. 創建一張內存圖片
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 2.獲得繪圖對象
        Graphics graphics = bufferedImage.getGraphics();

        // 3、繪製背景顏色
        graphics.setColor(Color.YELLOW);
        graphics.fillRect(0, 0, width, height);

        // 4、繪製圖片邊框
        graphics.setColor(Color.GRAY);
        graphics.drawRect(0, 0, width - 1, height - 1);

        // 5、輸出驗證碼內容
        graphics.setColor(Color.RED);
        graphics.setFont(new Font("宋體", Font.BOLD, 22));

        // 隨機輸出4個字符
        String s = "ABCDEFGHGKLMNPQRSTUVWXYZ23456789";
        Random random = new Random();

        // session中要用到
        String msg = "";

        int x = 5;
        for (int i = 0; i < charNum; i++) {
            int index = random.nextInt(32);
            String content = String.valueOf(s.charAt(index));

            msg += content;
            graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            graphics.drawString(content, x, 22);
            x += 20;
        }
        // 保存到session中
        request.getSession().setAttribute("scode",msg);

        // 6、繪製干擾線
        graphics.setColor(Color.GRAY);
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);

            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);
        }

        // 釋放資源
        graphics.dispose();

        // 圖片輸出 ImageIO
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());

    }

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

}

web

package com.itheima.web;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        try {
            //------------------------ 校驗驗證碼
            //a.獲取session中的驗證碼
            HttpSession session = request.getSession();
            String scode = (String) session.getAttribute("scode");
            // 刪除session中的驗證碼
            session.removeAttribute("scode");
            //b.獲取用戶輸入的驗證碼
            String ucode = request.getParameter("ucode");
            System.out.println(scode+" : "+ucode);
            //c.校驗
            if(ucode==null || ucode.equals("")){
                response.getWriter().print("驗證碼不可爲空..");
                return;
            }

            if(!ucode.equalsIgnoreCase(scode)){
                response.getWriter().print("驗證碼輸入錯誤..");
                return;
            }

            //-------------------------
            //1.編寫loginServlet
            //2.在servlet中獲取用戶名和密碼
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            //user.setUsername(map.get("username")[0]);
            //user.setPassword(map.get("password")[0]);
            //3.調用service處理業務邏輯
            BeanUtils.populate(user,map);
            UserService service = new UserService();
            User u = service.login(user);
            //4.判斷執行結果,生成響應信息
            if(u!=null){
                response.getWriter().print("登錄成功");
            }else {
                response.getWriter().print("登錄失敗");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().print("當前功能正在維護...");
        }
    }

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

總結:

1. 能夠說出會話的概念
    保存瀏覽器和服務器交互時產生的數據信息
2. 能夠說出cookie的概念
    瀏覽器
3. 能夠創建、發送、接收、刪除cookie
4. 能夠說出cookie執行原理
5. 能夠說出session的概念
6. 能夠獲取session對象、添加、刪除、獲取session中的數據
7. 能夠完成登錄驗證碼案例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章