當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
四、Web服务器——Session Cookie JSP入门 学习笔记
生活随笔
收集整理的這篇文章主要介紹了
四、Web服务器——Session Cookie JSP入门 学习笔记
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
今日內(nèi)容
1. 會話技術(shù)1. Cookie2. Session 2. JSP:入門學(xué)習(xí)會話技術(shù)
1. 會話:一次會話中包含多次請求和響應(yīng)。* 一次會話:瀏覽器第一次給服務(wù)器資源發(fā)送請求,會話建立,直到有一方斷開為止 2. 功能:在一次會話的范圍內(nèi)的多次請求間,共享數(shù)據(jù) 3. 方式:1. 客戶端會話技術(shù):Cookie2. 服務(wù)器端會話技術(shù):SessionCookie:
1. 概念:客戶端會話技術(shù),將數(shù)據(jù)保存到客戶端2. 快速入門:* 使用步驟:1. 創(chuàng)建Cookie對象,綁定數(shù)據(jù)* new Cookie(String name, String value) 2. 發(fā)送Cookie對象* response.addCookie(Cookie cookie) 3. 獲取Cookie,拿到數(shù)據(jù)* Cookie[] request.getCookies() 3. 實(shí)現(xiàn)原理* 基于響應(yīng)頭set-cookie和請求頭cookie實(shí)現(xiàn)4. cookie的細(xì)節(jié)1. 一次可不可以發(fā)送多個(gè)cookie?* 可以* 可以創(chuàng)建多個(gè)Cookie對象,使用response調(diào)用多次addCookie方法發(fā)送cookie即可。2. cookie在瀏覽器中保存多長時(shí)間?1. 默認(rèn)情況下,當(dāng)瀏覽器關(guān)閉后,Cookie數(shù)據(jù)被銷毀2. 持久化存儲:* setMaxAge(int seconds)1. 正數(shù):將Cookie數(shù)據(jù)寫到硬盤的文件中。持久化存儲。并指定cookie存活時(shí)間,時(shí)間到后,cookie文件自動失效2. 負(fù)數(shù):默認(rèn)值3. 零:刪除cookie信息3. cookie能不能存中文?* 在tomcat 8 之前 cookie中不能直接存儲中文數(shù)據(jù)。* 需要將中文數(shù)據(jù)轉(zhuǎn)碼---一般采用URL編碼(%E3)* 在tomcat 8 之后,cookie支持中文數(shù)據(jù)。特殊字符還是不支持,建議使用URL編碼存儲,URL解碼解析4. cookie共享問題?1. 假設(shè)在一個(gè)tomcat服務(wù)器中,部署了多個(gè)web項(xiàng)目,那么在這些web項(xiàng)目中cookie能不能共享?* 默認(rèn)情況下cookie不能共享* setPath(String path):設(shè)置cookie的獲取范圍。默認(rèn)情況下,設(shè)置當(dāng)前的虛擬目錄* 如果要共享,則可以將path設(shè)置為"/"2. 不同的tomcat服務(wù)器間cookie共享問題?* setDomain(String path):如果設(shè)置一級域名相同,那么多個(gè)服務(wù)器之間cookie可以共享* setDomain(".baidu.com"),那么tieba.baidu.com和news.baidu.com中cookie可以共享5. Cookie的特點(diǎn)和作用1. cookie存儲數(shù)據(jù)在客戶端瀏覽器2. 瀏覽器對于單個(gè)cookie 的大小有限制(4kb) 以及 對同一個(gè)域名下的總cookie數(shù)量也有限制(20個(gè))* 作用:1. cookie一般用于存出少量的不太敏感的數(shù)據(jù)2. 在不登錄的情況下,完成服務(wù)器對客戶端的身份識別6. 案例:記住上一次訪問時(shí)間1. 需求:1. 訪問一個(gè)Servlet,如果是第一次訪問,則提示:您好,歡迎您首次訪問。2. 如果不是第一次訪問,則提示:歡迎回來,您上次訪問時(shí)間為:顯示時(shí)間字符串2. 分析:1. 可以采用Cookie來完成2. 在服務(wù)器中的Servlet判斷是否有一個(gè)名為lastTime的cookie1. 有:不是第一次訪問1. 響應(yīng)數(shù)據(jù):歡迎回來,您上次訪問時(shí)間為:2018年6月10日11:50:202. 寫回Cookie:lastTime=2018年6月10日11:50:012. 沒有:是第一次訪問1. 響應(yīng)數(shù)據(jù):您好,歡迎您首次訪問2. 寫回Cookie:lastTime=2018年6月10日11:50:013. 代碼實(shí)現(xiàn):package cn.itcast.cookie;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.URLDecoder;import java.net.URLEncoder;import java.text.SimpleDateFormat;import java.util.Date;@WebServlet("/cookieTest")public class CookieTest extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//設(shè)置響應(yīng)的消息體的數(shù)據(jù)格式以及編碼response.setContentType("text/html;charset=utf-8");//1.獲取所有CookieCookie[] cookies = request.getCookies();boolean flag = false;//沒有cookie為lastTime//2.遍歷cookie數(shù)組if(cookies != null && cookies.length > 0){for (Cookie cookie : cookies) {//3.獲取cookie的名稱String name = cookie.getName();//4.判斷名稱是否是:lastTimeif("lastTime".equals(name)){//有該Cookie,不是第一次訪問flag = true;//有l(wèi)astTime的cookie//設(shè)置Cookie的value//獲取當(dāng)前時(shí)間的字符串,重新設(shè)置Cookie的值,重新發(fā)送cookieDate date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");String str_date = sdf.format(date);System.out.println("編碼前:"+str_date);//URL編碼str_date = URLEncoder.encode(str_date,"utf-8");System.out.println("編碼后:"+str_date);cookie.setValue(str_date);//設(shè)置cookie的存活時(shí)間cookie.setMaxAge(60 * 60 * 24 * 30);//一個(gè)月response.addCookie(cookie);//響應(yīng)數(shù)據(jù)//獲取Cookie的value,時(shí)間String value = cookie.getValue();System.out.println("解碼前:"+value);//URL解碼:value = URLDecoder.decode(value,"utf-8");System.out.println("解碼后:"+value);response.getWriter().write("<h1>歡迎回來,您上次訪問時(shí)間為:"+value+"</h1>");break;}}}if(cookies == null || cookies.length == 0 || flag == false){//沒有,第一次訪問//設(shè)置Cookie的value//獲取當(dāng)前時(shí)間的字符串,重新設(shè)置Cookie的值,重新發(fā)送cookieDate date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");String str_date = sdf.format(date);System.out.println("編碼前:"+str_date);//URL編碼str_date = URLEncoder.encode(str_date,"utf-8");System.out.println("編碼后:"+str_date);Cookie cookie = new Cookie("lastTime",str_date);//設(shè)置cookie的存活時(shí)間cookie.setMaxAge(60 * 60 * 24 * 30);//一個(gè)月response.addCookie(cookie);response.getWriter().write("<h1>您好,歡迎您首次訪問</h1>");}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}}JSP:入門學(xué)習(xí)
1. 概念:* Java Server Pages: java服務(wù)器端頁面* 可以理解為:一個(gè)特殊的頁面,其中既可以指定定義html標(biāo)簽,又可以定義java代碼* 用于簡化書寫!!!2. 原理* JSP本質(zhì)上就是一個(gè)Servlet3. JSP的腳本:JSP定義Java代碼的方式1. <% 代碼 %>:定義的java代碼,在service方法中。service方法中可以定義什么,該腳本中就可以定義什么。2. <%! 代碼 %>:定義的java代碼,在jsp轉(zhuǎn)換后的java類的成員位置。3. <%= 代碼 %>:定義的java代碼,會輸出到頁面上。輸出語句中可以定義什么,該腳本中就可以定義什么。4. JSP的內(nèi)置對象:* 在jsp頁面中不需要獲取和創(chuàng)建,可以直接使用的對象* jsp一共有9個(gè)內(nèi)置對象。* 今天學(xué)習(xí)3個(gè):* request* response* out:字符輸出流對象。可以將數(shù)據(jù)輸出到頁面上。和response.getWriter()類似* response.getWriter()和out.write()的區(qū)別:* 在tomcat服務(wù)器真正給客戶端做出響應(yīng)之前,會先找response緩沖區(qū)數(shù)據(jù),再找out緩沖區(qū)數(shù)據(jù)。* response.getWriter()數(shù)據(jù)輸出永遠(yuǎn)在out.write()之前5. 案例:改造Cookie案例Session:主菜
1. 概念:服務(wù)器端會話技術(shù),在一次會話的多次請求間共享數(shù)據(jù),將數(shù)據(jù)保存在服務(wù)器端的對象中。HttpSession 2. 快速入門:1. 獲取HttpSession對象:HttpSession session = request.getSession();2. 使用HttpSession對象:Object getAttribute(String name) void setAttribute(String name, Object value)void removeAttribute(String name) 3. 原理* Session的實(shí)現(xiàn)是依賴于Cookie的。4. 細(xì)節(jié):1. 當(dāng)客戶端關(guān)閉后,服務(wù)器不關(guān)閉,兩次獲取session是否為同一個(gè)?* 默認(rèn)情況下。不是。* 如果需要相同,則可以創(chuàng)建Cookie,鍵為JSESSIONID,設(shè)置最大存活時(shí)間,讓cookie持久化保存。Cookie c = new Cookie("JSESSIONID",session.getId());c.setMaxAge(60*60);response.addCookie(c);2. 客戶端不關(guān)閉,服務(wù)器關(guān)閉后,兩次獲取的session是同一個(gè)嗎?* 不是同一個(gè),但是要確保數(shù)據(jù)不丟失。tomcat自動完成以下工作* session的鈍化:* 在服務(wù)器正常關(guān)閉之前,將session對象系列化到硬盤上* session的活化:* 在服務(wù)器啟動后,將session文件轉(zhuǎn)化為內(nèi)存中的session對象即可。3. session什么時(shí)候被銷毀?1. 服務(wù)器關(guān)閉2. session對象調(diào)用invalidate() 。3. session默認(rèn)失效時(shí)間 30分鐘選擇性配置修改 <session-config><session-timeout>30</session-timeout></session-config>5. session的特點(diǎn)1. session用于存儲一次會話的多次請求的數(shù)據(jù),存在服務(wù)器端2. session可以存儲任意類型,任意大小的數(shù)據(jù)* session與Cookie的區(qū)別:1. session存儲數(shù)據(jù)在服務(wù)器端,Cookie在客戶端2. session沒有數(shù)據(jù)大小限制,Cookie有3. session數(shù)據(jù)安全,Cookie相對于不安全案例:驗(yàn)證碼
1. 案例需求:1. 訪問帶有驗(yàn)證碼的登錄頁面login.jsp2. 用戶輸入用戶名,密碼以及驗(yàn)證碼。* 如果用戶名和密碼輸入有誤,跳轉(zhuǎn)登錄頁面,提示:用戶名或密碼錯(cuò)誤* 如果驗(yàn)證碼輸入有誤,跳轉(zhuǎn)登錄頁面,提示:驗(yàn)證碼錯(cuò)誤* 如果全部輸入正確,則跳轉(zhuǎn)到主頁success.jsp,顯示:用戶名,歡迎您2. 分析:
目錄結(jié)構(gòu):
LoginServlet .java文件:
CheckCodeServlet .java文件:
package cn.web.servlet;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("/checkCodeServlet") public class CheckCodeServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int width = 100;int height = 50;// 1.創(chuàng)建一個(gè)對象,在內(nèi)存中畫圖(驗(yàn)證碼圖片對象)BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);// 2.美化圖片// 2.1 填充背景色Graphics g = image.getGraphics();// 畫筆對象g.setColor(Color.pink); // 設(shè)置畫筆顏色g.fillRect(0,0,width,height); // 填充一個(gè)矩形// 2.2 畫邊框g.setColor(Color.blue);g.drawRect(0,0,width-1,height-1);String str = "ABCDEFGHIJKLMNOPQRETUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";// 生成隨機(jī)下標(biāo)Random random = new Random();StringBuilder sb = new StringBuilder();for (int i = 1; i <= 4; i++) {int index = random.nextInt(str.length());// 獲取字符char c = str.charAt(index); // 根據(jù)下標(biāo)取出隨機(jī)字符sb.append(c);// 2.3 寫驗(yàn)證碼g.drawString(c+"",width/5*i,height/2);}String checkCode_session = sb.toString();// 將驗(yàn)證碼存入sessionrequest.getSession().setAttribute("checkCode_session",checkCode_session);// 2.4 畫干擾線g.setColor(Color.green);// 隨機(jī)生成坐標(biāo)點(diǎn)for (int i = 0; i < 10; i++) {int x1 = random.nextInt(width);int x2 = random.nextInt(width);int y1 = random.nextInt(height);int y2 = random.nextInt(height);g.drawLine(x1,y1,x2,y2);}// 3.將圖片輸出到頁面展示ImageIO.write(image,"jpg",response.getOutputStream());}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request,response);} }login.jsp文件:
<%--Created by IntelliJ IDEA.User: ZepDate: 2020/10/3Time: 10:37To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>login</title><style>div {color: red;}</style><script>window.onload = function () {document.getElementById("img").onclick = function () {var time = new Date().getTime();this.src = "/day16/checkCodeServlet?time=" + time;}}</script> </head> <body><form action="/day16/loginServlet" method="post"><table><tr><td>用戶名</td><td><input type="text" name="username"></td></tr><tr><td>密碼</td><td><input type="password" name="password"></td></tr><tr><td>驗(yàn)證碼</td><td><input type="text" name="checkCode"></td></tr><tr><td colspan="2"><img id="img" src="/day16/checkCodeServlet" alt=""></td></tr><tr><td colspan="2"><input type="submit" value="登錄"></td></tr></table></form><div><%= request.getAttribute("cc_error") == null ? "" : request.getAttribute("cc_error") %></div><div><%= request.getAttribute("login_error") == null ? "" : request.getAttribute("login_error") %></div></body> </html>success.jsp文件:
<%--Created by IntelliJ IDEA.User: ZepDate: 2020/10/3Time: 11:06To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head><title>success</title> </head> <body><h1><%= request.getSession().getAttribute("user") %>,歡迎您!</h1></body> </html>總結(jié)
以上是生活随笔為你收集整理的四、Web服务器——Session Cookie JSP入门 学习笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: selenium firefox驱动_P
- 下一篇: JS高级——await-async