当前位置:网站首页>Cookie & Session & kaptcha驗證碼
Cookie & Session & kaptcha驗證碼
2022-06-12 18:54:00 【蘇瞳呐】
文章目錄
Cookie
1. 概念
是服務器通知客戶端保存鍵值對的一種技術。
cookie 是 servlet(服務器) 發送到 Web 瀏覽器(客戶端)的少量信息,這些信息由瀏覽器保存,然後發送回服務器。
客戶端有了 cookie 後,每次請求都發送給服務器
每個 cookie 的大小不能超過 4 KB。
2. 創建Cookie
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//1. 創建Cookie對象
Cookie cookie = new Cookie("key1", "value1");
//2. 通知客戶端保存
resp.addCookie(cookie);
resp.getWriter().write("Cookie創建成功");
}
3. 服務器獲取Cookie
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
//System.out.println(cookie);
resp.getWriter().write("Cookie["+ cookie.getName() + " = " + cookie.getValue() + "] <br/>");
}
// 查找特定的Cookie (項目中會把這個寫成工具類)
Cookie need = null;
for (Cookie cookie : cookies) {
if ("key2".equals(cookie.getName())) {
need = cookie;
break;
}
}
if (need != null) {
// 不等於null,說明賦過值
resp.getWriter().write("找到了需要的Cookie");
}
}
CookieUtils.java
// 查找特定的Cookie
public static Cookie findCookie(Cookie[] cookies, String name) {
if (cookies == null || name == null || cookies.length == 0) {
return null;
}
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
4. Cookie的修改
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) {
// 第一種
// 修改需要先創建同key的Cookie對象,新值直接構造傳入就行
Cookie newCookie1 = new Cookie("key1", "newValue1");
resp.addCookie(newCookie1); // 保存修改
// 第二種
Cookie newCookie2 = CookieUtils.findCookie(req.getCookies(), "key2");
if (newCookie2 != null) {
newCookie2.setValue("newValue2"); // !注意不支持中文和一些符號,需要的話可以使用BASE64編碼
resp.addCookie(newCookie2);
}
}
5. Cookie的生命控制
Cookie的生命控制,即Cookie什麼時候銷毀
API:setMaxAge(int expiry)
- 正值錶示 cookie 將在經過該值錶示的秒數後過期 (關閉瀏覽器再次訪問還在)
- 負值意味著 cookie 不會被持久存儲,將在 Web 瀏覽器退出時删除 (默認是負數,-1)
- 0 值錶示馬上删除 cookie。
修改後記得 resp.addCookie(cookie);
6. Cookie的有效路徑Path
有效路徑Path 可以過濾哪些Cookie可以發送給服務器,那些不發。
Path是通過請求的地址來進行有效的過濾
例如:
cookie1 path=/工程路徑
cookie2 path=/工程路徑/abc
請求地址: (默認是當前的工程路徑)
http://ip:port/工程路徑/a.html 則cookie1會發送給服務器,cookie2不發送
http://ip:port/工程路徑/abc/d.html cookie2,cookie1都發送!!
Cookie cookie = new Cookie("path1", "path1");
cookie.setPath(req.getContextPath() + "/abc"); // -> /工程路徑/abc
7. Cookie應用-免用戶名密碼登錄
前端:login.jsp
<form action="/dynamicobject/loginServlet" method="post">
用戶名: <input type="text" name="username" value="${cookie.username.value}"> <br/>
密碼: <input type="password" name="password" value="${cookie.password.value}"> <br/>
<input type="submit" value="登錄">
</form>
後端:LoginServlet.java
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
String username = req.getParameter("username");
String password = req.getParameter("password");
// 這裏可以去數據庫查找,我們這裏寫死了
if ("sutong".equals(username) && "123456".equals(password)) {
Cookie c1 = new Cookie("username", username);
c1.setMaxAge(60 * 60 * 24 * 7); // 一周內有效
resp.addCookie(c1);
Cookie c2 = new Cookie("password", password); // 一般密碼都會加密的
c2.setMaxAge(60 * 60 * 24 * 7);
resp.addCookie(c2);
System.out.println("登陸成功!");
} else {
System.out.println("登陸失敗!");
}
}
}
Session
1. 概念
Session是一個接口(HttpSession),就是會話。
用來維護一個客戶端和服務器之間關聯的一種技術。
每個客戶端都有它自己的一個Session。
Session會話中,我們經常用來保存用戶登錄之後的信息。
2. 創建和獲取Session
創建和獲取都是一個函數 request.getSession()
第一次調用是創建Session,之後調用都是獲取前面創建好的Sesson會話對象
isNew() : 判斷是不是剛創建出來的(是不是新的)
getId() : 每個會話都會有個唯一id值
protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
HttpSession session = req.getSession(); // 創建或獲取Session
boolean flag = session.isNew(); // 判斷是否剛創建
String id = session.getId(); // id
resp.getWriter().write("得到的Session的Id是" + id + "<br/>");
resp.getWriter().write("這個Session是否剛創建" + flag);
}
3. Session域數據的存取
存取:
HttpSession session = req.getSession();
session.setAttribute("key1", "value1");
獲取:
String att = (String) req.getSession().getAttribute("key1"); // 返回的是Object
4. Session的生命周期的控制
API:public void setMaxInactiveInterval(int interval)
設置Session的超時時間(秒為單比特),超過時長就會被銷毀(是最大不活躍間隔!)
正數是超時時長,負數是永不超時。注意:0不是立即銷毀,立即銷毀是session.invalidate()
獲取方法:public int getMaxInactiveInterval()
默認是1800秒,即半小時。
因為在Tomcat的服務器的配置文件web.xml中,有寫<session-timeout>30</session-timeout>
如果我希望我們工程的Session不想是30分鐘,可以在自己項目下的web.xml做以上相同的配置,就可以修改工程下所有Session的默認超時時長了。
<session-config>
<session-timeout>20</session-timeout> <!-- 分鐘為單比特-->
</session-config>
如果只想修改個別Session的超時時長,則需要使用session.setMaxInactiveInterval(interval) 方法
超時時長:指的是客戶端兩次請求的最大間隔時長!!
5. 瀏覽器和Session的關聯
當客戶端沒有Cookie信息的時候,發送請求,服務器會(調用req.getSession())創建Session對象,每次創建Session會話的時候,都會創建一個Cookie對象,這個Cookie對象的key永遠是:JSESSIONID,value是新創建出來的Session的Id。然後通過響應頭返回給客戶端。
當客戶端有了這個Cookie之後,每次請求會把Session的Id以Cookie的形式發送給服務器,然後服務器這邊會通過Id查找自己之前創建好的Session對象(調用req.getSession()),並返回。
如果上次創建的Session的沒過期的時候,我們手動把Cookie信息删掉的話,服務器就沒法通過得到id,就沒法找到之前的那個Session對象,客戶端發送請求的時候,服務器則會重新創建新的Session會話,重複上面的操作。
Session 技術,底層其實是基於 Cookie 技術來實現的
kaptcha驗證碼
驗證碼可以解决錶單重複提交的情况
1. 使用
我們可以使用第三方的jar包,穀歌驗證碼,kaptcha-2.3.2.jar
- 導包
- 在 web.xml 中去配置用於生成驗證碼的Servlet程序 (即com.google.code.kaptcha.servlet.KaptchaServlet這個類,穀歌寫的)
<servlet>
<servlet-name>KaptchaServlet</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>KaptchaServlet</servlet-name>
<!-- 注意這裏改的訪問名(看起來像個圖片),這樣的話訪問這個就是自動生成驗證碼和圖片,並保存到Session域-->
<url-pattern>/kaptcha.jpg</url-pattern>
</servlet-mapping>
- 在錶單中使用 img標簽去顯示驗證碼並使用它
<form action="" method="post">
用戶名:<input type="text" name="username"> <br/>
密碼:<input type="password" name="password"> <br/>
驗證碼:<input type="text" name="code"> <br/>
<img id="code_img" src="http://localhost:8080/book/kaptcha.jpg" alt="圖片找不到"> <br/>
<input type="button" value="注册">
</form>
在服務器獲取穀歌生成的驗證碼和客戶端發來的驗證碼比較使用 (獲取後記得馬上删除)
獲取穀歌生成的驗證碼 :
req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);獲取用戶提交的驗證碼:
req.getSession().getAttribute("code")
2. 驗證碼的切換
// 給驗證碼圖片綁定單機事件
$("#code_img").click(function () {
// 但這樣每次發一樣的請求,可能會被瀏覽器的緩存導致驗證碼無法改變,
// 緩存是根據工程名後面的資源名和參數產生的,所以我們可以在後面加上一個隨機的參數跳過緩存
//this.src = "http://localhost:8080/book/kaptcha.jpg";
this.src = "http://localhost:8080/book/kaptcha.jpg?d=" + new Date(); // 可以加個時間戳
});
边栏推荐
- CVPR 2022 Oral 大连理工提出SCI:快速、超强的低光照图像增强方法
- Have a meal, dry pot, fat intestines + palm treasure!
- Why my order by create_ Time ASC becomes order by ASC
- Kali LAN ARP Spoofing and monitoring other hosts' Internet access records in the LAN
- 笔记本电脑清灰打硅脂后,开机一直黑屏,如何破?
- 每日一博 - 微服务权限一二事
- SCI Writing - Methodology
- leetcode:5259. Calculate the total tax payable [simple simulation + see which range]
- MySQL advanced learning notes
- Delivery lead time lightweight estimation practice - Notes
猜你喜欢

CVPR 2022 oral Dalian Institute of technology proposed SCI: a fast and powerful low light image enhancement method

What is SAP support package stack

io. seata. common. exception. FrameworkException: can not connect to services-server.

论大型政策性银行贷后,如何数字化转型 ?-亿信华辰

Uniapp uses the Ali Icon

从应无所住说起

数据库全量SQL分析与审计系统性能优化之旅

To understand Devops, you must read these ten books!

【0008】无序列表

chrome浏览器解决跨域问题
随机推荐
leetcode:6094. 公司命名【分组枚举 + 不能重复用set交集 + product笛卡儿积(repeat表示长度)】
leetcode:6095. 强密码检验器 II【简单模拟 + 不符合直接False】
国内如何下载Vega
ISCC2022
[today in history] June 12: the United States entered the era of digital television; Mozilla's original developer was born; 3com merges with American Robotics
Leetcode 494. 目标和
Istio 1.14 release
MySQL数据库(28):变量 variables
【0008】无序列表
Chrome browser solves cross domain problems
美团获得小样本学习榜单FewCLUE第一!Prompt Learning+自训练实战
Tarfile decompress nested tar
Delivery lead time lightweight estimation practice - Notes
The difference between user status and system status in CRM
I was badly hurt by the eight part essay...
Double non grind one, three side byte, cool. Next time
每日一博 - 微服务权限一二事
Vue - Advanced Vue router routing (2) (replace attribute, programming route navigation, caching route components, and exclusive hooks for routes)
Experiment 10 Bezier curve generation - experiment improvement - interactive generation of B-spline curve
Research Report on the overall scale, major manufacturers, major regions, products and applications of Electric Screwdrivers in the global market in 2022