Cookie是客戶端技術,程序把每個用戶的數據以cookie的形式寫給用戶各自的瀏覽器。當用戶使用瀏覽器再去訪問服務器中的web資源時,就會帶着各自的數據去。
這樣web資源處理的就是用戶各自的數據了。
Session
Session是服務器端技術,利用這個技術,服務器在運行時可以為每一個用戶的瀏覽器創建一個其獨享的session對象,由於session為用戶瀏覽器獨享,所以用戶在訪問服務器
的web資源時,可以把各自的數據放在各自的session中,當用戶再去訪問服務器中的其他web資源時,其他web資源再從用戶各自的session中取出數據為用戶服務。
什么是會話?用戶打開瀏覽器,訪問站點,連續進行多次操作,關閉瀏覽器,整個過程稱為會話。
管理HTTP協議會話狀態:Cookie和Session
Cookie:將用戶相關數據,保存客戶端,用戶每次訪問服務器自動攜帶cookie數據。
Session:將用戶相關數據保存服務器端,為每個客戶端生成一個獨立Session數據對象,通過對象唯一編號,區分哪個瀏覽器對應哪個Session
Cookie
Cookie快速入門案例:(上次訪問時間)
eg:
package cn.lsl.cookie; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LastVisitServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie[] cookies = request.getCookies(); response.setContentType("text/html;charset=utf-8"); if(cookies == null){ //當前時間毫秒等價new Date().getTime() long now = System.currentTimeMillis(); //向客戶端寫出cookie需要用到cookie Cookie cookie = new Cookie("last", now+""); response.addCookie(cookie); response.getWriter().println("歡迎第一次訪問本網站"); }else{ for (Cookie cookie : cookies) { if(cookie.getName().equals("last")){ long lasttime = Long.parseLong(cookie.getValue()); //顯示給用戶 Date date = new Date(lasttime); //格式化日期 DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒"); response.getWriter().println("上次訪問時間:" + dateFormat.format(date)); } } long now = System.currentTimeMillis(); Cookie cookie = new Cookie("last", now+""); response.addCookie(cookie); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
分析:
1、通過服務器向客戶端寫cookie
Cookie cookie = new Cookie(name,value);
response.addCookie(cookie);
* 在HTTP協議響應頭信息中 Set-Cookie: last=1339556457609
2、當客戶端存在cookie之后,以后每次請求自動攜帶 HTTP協議請求頭信息 Cookie: last=1339556456859
服務器端獲得需要cookie數據
Cookie[] cookies = request.getCookies(); ---- 獲得客戶端所有cookie
if(cookies==null){} 判斷cookie是否存在
遍歷cookie獲得需要信息
for (Cookie cookie : cookies) {
// 獲得每個cookie
if (cookie.getName().equals("last")) {
// 找到了需要cookie
}
}
CookieAPI詳解
1.將cookie寫回客戶端 response.addCookie(cookie);
2.讀取請求中cookie信息 request.getCookies
3.Cookie對象創建 new Cookie(name,value)
*cookie的name不允許改變
什么是會話cookie,什么是持久cookie?
cookie信息默認情況保存在瀏覽器內存中 ---- 會話cookie
會話cookie會在關閉瀏覽器時清除
持久Cookie,cookie數據保存客戶端硬盤上
通過setMaxAge設置Cookie為持久Cookie
* 在JavaAPI 中所有與時間相關參數,int 類型 單位秒, long類型 單位毫秒
eg:
package cn.lsl.cookie; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LastVisitServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", -1); response.setHeader("Pragma", "no-cache"); Cookie[] cookies = request.getCookies(); response.setContentType("text/html;charset=utf-8"); if(cookies == null){ //當前時間毫秒等價new Date().getTime() long now = System.currentTimeMillis(); //向客戶端寫出cookie需要用到cookie Cookie cookie = new Cookie("last", now+""); cookie.setPath("/Cookie"); //設置cookie有效時間 cookie.setMaxAge(60*60*24*2); response.addCookie(cookie); response.getWriter().println("歡迎第一次訪問本網站"); }else{ for (Cookie cookie : cookies) { if(cookie.getName().equals("last")){ long lasttime = Long.parseLong(cookie.getValue()); //顯示給用戶 Date date = new Date(lasttime); //格式化日期 DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒"); response.getWriter().println("上次訪問時間:" + dateFormat.format(date)); } } long now = System.currentTimeMillis(); Cookie cookie = new Cookie("last", now+""); cookie.setPath("/Cookie"); //設置cookie有效時間 cookie.setMaxAge(60*60*24*2); response.addCookie(cookie); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
訪問cookie有效路徑path
默認情況下,生成cookie時,產生默認有效訪問路徑 (默認生成cookie程序路徑)
http://localhost/Cookie/lastvisit --- 生成cookie --- path 默認值: /Cookie
http://localhost/Cookie/servlet/path ---- 生成cookie ---- path 默認值:/Cookie/servlet
第二次訪問程序攜帶cookie信息,如果訪問路徑與path不一致,不會攜帶cookie 信息
company cookie : path --- /Cookie/serlvet
last cookie : path --- /Cookie
訪問 :http://localhost/Cookie/servlet/path ---- 同時滿足/Cookie/serlvet、/Cookie 攜帶 company 和 last兩個cookie信息
訪問 :http://localhost/Cookie/lastvisit ---- 滿足 /Cookie 不滿足/Cookie/serlvet 攜帶 last 一個cookie 信息
* 以后程序開發,盡量設置path ---- setPath方法
第一方cookie 和 第三方cookie
通過setDomain 設置cookie 有效域名
訪問google時,生成cookie過程中 cookie.setDomain(".baidu.com") ---- 生成百度cookie ------ 第三方cookie
* 第三方cookie 屬於不安全 ----- 一般瀏覽器不接受第三方cookie
訪問google時,生成cookie,cookie.setDomain(.google.con) ---- 生成google的cookie ------ 第一方cookie
刪除Cookie
案例:刪除上次訪問時間
原理:設置cookie MaxAge為 0
*刪除cookie必須設置path與cookie的path一致
eg:
package cn.lsl.cookie; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DeleteCookieServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = new Cookie("last", ""); cookie.setMaxAge(0); //path一致 cookie.setPath("/Cookie"); response.addCookie(cookie); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
歷史瀏覽記錄案例
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@page import="cn.lsl.cookie.CookieUtils"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>product.jsp</title> </head> <body> <h1>商品列表</h1> <a href="/Cookie/producthistory?id=1">冰箱</a><br/> <a href="/Cookie/producthistory?id=2">洗衣機</a><br/> <a href="/Cookie/producthistory?id=3">筆記本電腦</a><br/> <a href="/Cookie/producthistory?id=4">手機</a><br/> <a href="/Cookie/producthistory?id=5">空調</a><br/> <a href="/Cookie/producthistory?id=6">熱水器</a><br/> <a href="/Cookie/producthistory?id=7">微波爐</a><br/> <a href="/Cookie/producthistory?id=8">電風扇</a><br/> <h1>商品瀏覽記錄</h1><h3><a href="/Cookie/cleanhistory">清空瀏覽記錄</a></h3> <% Cookie cookie = CookieUtils.findCookie(request.getCookies(),"history"); if(cookie == null){ out.println("無瀏覽記錄!"); }else{ String ids = cookie.getValue(); String[] idArray = ids.split(","); String[] arr = { "冰箱", "洗衣機", "筆記本電腦", "手機", "空調", "熱水器", "微波爐", "電風扇" }; for(String id : idArray){ out.println(arr[Integer.parseInt(id)-1]+"<br/>"); } } %> </body> </html>
package cn.lsl.cookie; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ProductHistoryServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] arr = { "冰箱", "洗衣機", "筆記本電腦", "手機", "空調", "熱水器", "微波爐", "電風扇" }; //獲得用戶點擊查看商品編號 String id = request.getParameter("id"); response.setContentType("text/html;charset=utf-8"); response.getWriter().println("用戶正在瀏覽商品:" + arr[Integer.parseInt(id) - 1]); response.getWriter().println("<a href='/Cookie/product.jsp'>返回</a>"); Cookie cookie = CookieUtils.findCookie(request.getCookies(), "history"); if(cookie == null){ cookie = new Cookie("history", id); cookie.setMaxAge(60 * 60); cookie.setPath("/Cookie"); response.addCookie(cookie); }else{ //已存在商品瀏覽記錄,判斷當前瀏覽商品是否已經在記錄中 String ids = cookie.getValue(); String[] idArray = ids.split(","); for(String existId : idArray){ if(existId.equals(id)){ //當前瀏覽商品已經在瀏覽器記錄中 return; } } //當前id沒有在瀏覽器記錄中 cookie.setValue(ids + "," + id); cookie.setMaxAge(60 * 60); cookie.setPath("/Cookie"); response.addCookie(cookie); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
package cn.lsl.cookie; import javax.servlet.http.Cookie; public class CookieUtils { /** * 在Cookie數組中查找指定name cookie */ public static Cookie findCookie(Cookie[] cookies, String name){ if(cookies == null){ return null; }else{ for (Cookie cookie : cookies) { if(cookie.getName().equals(name)){ return cookie; } } return null; } } }
package cn.lsl.cookie; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CleanHistoryServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = new Cookie("history",""); cookie.setMaxAge(0); cookie.setPath("/Cookie"); response.addCookie(cookie); //跳轉到商品列表頁面:重定向 response.sendRedirect("/Cookie/product.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
Session
1.Session是服務器端會話管理技術,服務器會為每個瀏覽器創建一個單獨Session對象,保存該瀏覽器(會話)操作相關信息。
與Cookie區別:cookie是保存在客戶端,Session保存在服務器端
2.為什么有Cokie技術?還需要Session?
Cookie存在客戶端---- 存在安全問題
Session將數據存在服務器,數據更加安全
*Session將數據保存在服務器端,占用服務器內存資源,Cookie不會占用服務器資源
例如:京東購物車信息保存Cookie,淘寶購物車信息保存Session
3.Session共享
實驗:用IE6 向Session保存一個數據,用另一個IE6讀取數據?
用第一個IE6保存session數據,當前瀏覽器可以獲得,但是第二個IE6 無法獲得第一個瀏覽器保存Session 數據
IE8以上或火狐瀏覽器當打開多個瀏覽器窗口,之間Session共享
原因:IE6的cookie中保存jsessionId默認是會話級別;IE8或者火狐的cookie中保存jsessionId默認是持久cookie
三個問題:
問題一:如何讓多個IE6 共享同一個Session ---- 將session id 持久化
問題二:如果客戶端關閉瀏覽器,是否就刪除了Session ?
沒有,Session保存在服務器端
問題三:IE6 保存Session,關閉瀏覽器,再次打開,數據丟失了?
IE6默認jsessionId保存會話Cookie中,關閉瀏覽器,會話cookie就會被刪除,客戶端丟失jsessionid 無法找到服務器對應Session對象
* 服務器Session對象還存在
案例一:實現多個瀏覽器的session共享和關閉瀏覽器再次打開數據還存在
package cn.lsl.session; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class WriteSessionServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲得Session對象 HttpSession httpSession = request.getSession(); //向session保存一個數據 httpSession.setAttribute("company", "軟件公司"); //將寫回給瀏覽器JSESSIONID持久化 Cookie cookie = new Cookie("JSESSIONID", httpSession.getId()); cookie.setMaxAge(60 * 60); cookie.setPath("/SessionTest"); response.addCookie(cookie); response.setContentType("text/html;charset=utf-8"); response.getWriter().println("已向session保存一個數據!"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
package cn.lsl.session; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ReadSessionServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession httpSession = request.getSession(); response.setContentType("text/html;charset=utf-8"); response.getWriter().println("讀取之前保存session信息:" + httpSession.getAttribute("company")); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
Session購物車案例
1、商品列表、用戶點擊列表中商品、將商品添加購物車
2、查看購物車中商品,以及商品購買件數
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>product.jsp</title> </head> <body> <h1>商品列表</h1> 冰箱 <a href="/SessionTest/buy?id=1">購買</a> <br/> 洗衣機 <a href="/SessionTest/buy?id=2">購買</a> <br/> 熱水器 <a href="/SessionTest/buy?id=3">購買</a> <br/> 微波爐 <a href="/SessionTest/buy?id=4">購買</a> <br/> 空調 <a href="/SessionTest/buy?id=5">購買</a> <br/> 電飯鍋 <a href="/SessionTest/buy?id=6">購買</a> <br/> </body> </html>
package cn.lsl.session; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class BuyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲得購買商品編號 String id = request.getParameter("id"); //根據編號得到商品名稱 String[] arr = { "冰箱", "洗衣機", "熱水器", "微波爐", "空調", "電飯鍋" }; String productName = arr[Integer.parseInt(id)-1]; //判斷商品名稱是否在購物車中 //先判斷購物車是否存在 Map<String, Integer> cart = (Map<String, Integer>) request.getSession().getAttribute("cart");//可能返回null if(cart == null){ //購物車對象不存在 cart = new HashMap<String, Integer>(); } // Map containsKey(String Key),判斷key有沒有對應的value值;有,則返回true if(cart.containsKey(productName)){ //購物車存在該商品,數量+1 int number = cart.get(productName); cart.put(productName, number+1); }else{ //商品沒有在購物車中 cart.put(productName, 1); } //將購物車加入session request.getSession().setAttribute("cart", cart); response.setContentType("text/html;charset=utf-8"); response.getWriter().println("商品已經被加入購物車!"); response.getWriter().println("<a href='/SessionTest/cart.jsp'>查看購物車</a>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>cart.jsp</title> </head> <body> <h1>查看購物車</h1> <h3><a href="/SessionTest/invalidate.jsp">清空購物車</a></h3> <!-- 購物車信息保存session中 Map<String, Integer> --> <% Map<String, Integer> cart = (Map<String,Integer>)request.getSession().getAttribute("cart"); if(cart == null){ out.println("無購物信息"); }else{ for(String productName : cart.keySet()){ out.println("<h3>商品名稱:"+productName+",數量:" + cart.get(productName)+"</h3>"); } } %> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!-- 清空購物車 --> <% //銷毀Session request.getSession().invalidate(); response.sendRedirect("/SessionTest/cart.jsp"); %>
4.禁用Cookie后,Session還能否使用?
可以,可以對url進行重寫,原理在url;jsessionid=xxx ---- 在程序中可以調用response.encodeURL進行URL重寫
* 如果服務器進行URL重寫,所有路徑都必須重寫
5.Cookie生命周期和Session生命周期
Cookie生命周期
創建:Cookie cookie = new Cookie(name,value); response.add(cookie);
銷毀:會話cookie會在瀏覽器關閉時銷毀,持久cookie會在cookie過期(MaxAge)后銷毀
Session生命周期
創建:request.getSession()創建session
銷毀:三種:1.服務器關閉時銷毀 2.session過期時銷毀 3.手動調用session.invalidate
設置session過期時間
1、配置web.xml
<session-config>
<session-timeout>30</session-timeout>
</session-config>
2、調用session對象 setMaxInactiveInterval(int interval) 單位是秒
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60*60); 設置session過期時間1小時
用戶登陸案例和一次性驗證碼:
驗證碼從session獲取后,馬上刪除 ---- 驗證碼只能使用一次
eg:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'login.jsp' starting page</title> <script type="text/javascript"> function change(){ //切換驗證碼 document.getElementById("myimg").src="/SessionTest/checkcode?"+new Date().getTime(); } </script> </head> <body> <h1>登陸頁面</h1> <h3 style="color:red;">${requestScope.msg}</h3> <form action="/SessionTest/login" method="post"> 用戶名<input type="text" name="username" /><br/> 密碼<input type="password" name="password" /><br/> 請輸入驗證碼<input type="text" name="checkcode" /><img id="myimg" src="/SessionTest/checkcode" style="cursor:pointer;" onclick="change();"><br/> <input type="submit" value="登陸" /> </form> </body> </html>
package cn.lsl.session; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { private Map<String, String> userInfo = new HashMap<String, String>(); @Override public void init() throws ServletException { //制作用戶數據 userInfo.put("aaa", "111"); userInfo.put("bbb", "222"); userInfo.put("ccc", "333"); userInfo.put("ddd", "444"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //中文驗證碼,需要解決亂碼問題 request.setCharacterEncoding("utf-8"); //判斷驗證碼輸入是否正確 String checkcode = request.getParameter("checkcode"); String checkcode_session = (String)request.getSession().getAttribute("checkcode_session"); //刪除session中驗證碼 request.getSession().removeAttribute("checkcode_session"); if(checkcode_session == null || !checkcode_session.equals(checkcode)){ //傳遞出錯錯誤信息給jsp request.setAttribute("msg", "驗證碼錯誤"); request.getRequestDispatcher("/login.jsp").forward(request, response); return; } //從請求中獲得數據 String username = request.getParameter("username"); String password = request.getParameter("password"); //判斷用戶信息是否正確 if(userInfo.containsKey(username)){ //如果用戶名存在 if(userInfo.get(username).equals(password)){ //密碼正確 -- 登陸成功 //將用戶信息保存session request.getSession().setAttribute("username", username); //跳轉登陸成功,系統主頁 response.sendRedirect("/SessionTest/welcome.jsp"); }else{ request.setAttribute("msg", "密碼碼錯誤"); request.getRequestDispatcher("/login.jsp").forward(request, response); } }else{ //用戶名不存在 request.setAttribute("msg", "用戶名不存在"); request.getRequestDispatcher("/login.jsp").forward(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
package cn.lsl.session; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CheckcodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.setHeader("Cache-Control", "no-cache"); // response.setDateHeader("Expires", -1); // response.setHeader("Pragma", "no-cache"); int width = 120; int height = 30; //創建一張內存中緩沖圖片 BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); //背景色 Graphics graphics = bufferedImage.getGraphics(); //通過graphics對象繪制圖片 graphics.setColor(Color.YELLOW); graphics.fillRect(0, 0, width, height); //邊框 graphics.setColor(Color.BLUE); graphics.drawRect(0, 0, width-1, height-1); //寫驗證內容 Graphics2D graphics2d = (Graphics2D)bufferedImage.getGraphics(); graphics2d.setColor(Color.RED); graphics2d.setFont(new Font("宋體",Font.BOLD,18)); //String content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; String content = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a" + "\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b" + "\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a" + "\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341" + "\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979" + "\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11" + "\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8" + "\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a" + "\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700" + "\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1" + "\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e" + "\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80" + "\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8" + "\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66" + "\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1" + "\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b" + "\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173" + "\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1" + "\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b" + "\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b" + "\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc" + "\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73" + "\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440" + "\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5" + "\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2" + "\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357" + "\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1" + "\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027" + "\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55" + "\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a" + "\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6"; //內容四個字 -- 隨機從content中抽取四個字 Random random = new Random(); int x=10; int y=20; StringBuffer stringBuffer = new StringBuffer(); for(int i=0; i<4; i++){ //為字生成旋轉角度 -30 -- 30 double jiaodu = random.nextInt(60) - 30; //將旋轉角度換算弧度 double theta = jiaodu/180*Math.PI; System.out.println(theta); int index = random.nextInt(content.length()); char letter = content.charAt(index); stringBuffer.append(letter); graphics2d.rotate(theta, x, y); graphics2d.drawString(letter+"", x, y); //將角度還原 graphics2d.rotate(-theta, x, y); x += 30; } //將StringBuffer中四個字轉換String String checkcode = stringBuffer.toString(); //將驗證碼存入session request.getSession().setAttribute("checkcode_session", checkcode); //繪制隨機干擾線 int x1; int x2; int y1; int y2; graphics.setColor(Color.LIGHT_GRAY); for(int i=0; i<10; i++){ x1 = random.nextInt(width); x2 = random.nextInt(width); y1 = random.nextInt(height); y2 = random.nextInt(height); //根據兩點 繪制直線 graphics.drawLine(x1, y1, x2, y2); } //內存中資源釋放 graphics.dispose(); //將圖片輸出到瀏覽器 ImageIO //將內存的圖片通過瀏覽器輸出流寫成jpg格式圖片 ImageIO.write(bufferedImage, "jpg", response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>welcome.jsp</title> </head> <body> <h1>系統主頁</h1> <% //因為session會保存登陸用戶信息,如果session中沒有該信息,說明用戶未登陸 if(request.getSession().getAttribute("username")==null){ out.println("你還沒有登陸,<a href='/SessionTest/login.jsp'>去登陸</a>"); }else{ //已經登陸 out.println("歡迎你," + request.getSession().getAttribute("username")); } %> </body> </html>
Servlet三種數據范圍總結:
ServletContext
HttpServletRequest
HttpSession
三種數據范圍,每個對象各自維護類似map集合結構,具備相同幾個方法
setAttribute 存入一個屬性
getAttribute 取出一個屬性
removeAttribute 移除一個屬性
三種數據范圍對象在哪些情況使用?
ServletContext服務器啟動時創建,服務器關閉銷毀,所有Servlet共享 --- 保存一些全局數據
例如:數據庫連接池、工程配置屬性、配置文件內容
HttpSession 在request.getSession時創建,在三種情況下銷毀 ----- 保存與用戶相關數據
例如:系統登陸信息、購物車數據
HttpServletRequest在客戶端發起請求時,服務器創建對象,在響應結束時,對象銷毀 ---- 保存Servlet向JSP傳輸數據信息
例如:執行某個操作,Servlet將操作結果傳遞JSP(Servlet將登陸錯誤信息傳遞JSP)、Servlet將數據查詢結果傳遞JSP
以上三種數據范圍 ServletContext > HttpSession > HttpServletRequest
*宗旨:優先使用生命周期短的