概念:客戶端會話技術,將數據保存到客戶端javascript
使用步驟:css
1 package cn.testRep.web.servlet.cookie;
2
3 import javax.servlet.ServletException;
4 import javax.servlet.annotation.WebServlet;
5 import javax.servlet.http.Cookie;
6 import javax.servlet.http.HttpServlet;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9 import java.io.IOException;
10
11 @WebServlet("/servletCookieDemo1")
12 public class ServletCookieDemo1 extends HttpServlet {
13 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
14
15
16 //1建立cookie對象
17 Cookie cookie = new Cookie("msg","hello");
18 //2發送cookie給瀏覽器
19 response.addCookie(cookie);
20
21 }
22
23 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
24 this.doPost(request,response);
25
26 }
27 }
1 package cn.testRep.web.servlet.cookie;
2
3 import javax.servlet.ServletException;
4 import javax.servlet.annotation.WebServlet;
5 import javax.servlet.http.Cookie;
6 import javax.servlet.http.HttpServlet;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9 import java.io.IOException;
10
11 @WebServlet("/servletCookieDemo2")
12 public class ServletCookieDemo2 extends HttpServlet {
13 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
14
15 //獲取客戶端的Cookie
16 Cookie[] cookie = request.getCookies();
17 //遍歷Cookies
18 if(cookie != null){
19 for (Cookie c: cookie) {
20 String name = c.getName();
21 String value = c.getValue();
22 System.out.println(name+":"+value);
23 }
24 }
25
26 }
27
28 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
29 this.doPost(request,response);
30
31 }
32 }
一次可不能夠發送多個cookie?html
cookie在瀏覽器中保存多長時間?java
cookie能不能存中文?web
cookie共享問題?
問: 假設在一個tomcat服務器中,部署了多個web項目,那麼在這些web項目中cookie能不能共享?
答: 默認狀況下cookie不能共享,可是setPath(String path)可設置cookie的獲取範圍。默認狀況下,設置當前的虛擬目錄,若是要共享,則能夠將path設置爲"/"。即IP地址下的項目均可以共享。數據庫
問: 不一樣的tomcat服務器間cookie共享問題?
答: setDomain(String path):若是設置一級域名相同,那麼多個服務器之間cookie能夠共享,
如 setDomain(".baidu.com"),那麼tieba.baidu.com和news.baidu.com中cookie能夠共享瀏覽器
Cookie的特色和做用緩存
需求:tomcat
分析:安全
代碼實現:
1package cn.testRep.web.servlet.cookie;
2
3import javax.servlet.ServletException;
4import javax.servlet.annotation.WebServlet;
5import javax.servlet.http.Cookie;
6import javax.servlet.http.HttpServlet;
7import javax.servlet.http.HttpServletRequest;
8import javax.servlet.http.HttpServletResponse;
9import java.io.IOException;
10import java.net.URLDecoder;
11import java.net.URLEncoder;
12import java.text.SimpleDateFormat;
13import java.util.Calendar;
14import java.util.Date;
15import java.util.logging.SimpleFormatter;
16
17@WebServlet("/servletCookieDemo1")
18public class ServletCookieDemo1 extends HttpServlet {
19 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20
21 //設置響應的消息體數據格式以及編碼
22 response.setContentType("text/html;charset=utf-8");
23 //定義一個標記
24 boolean flag =false;
25
26 //獲取客戶端的Cookie
27 Cookie[] cookie = request.getCookies();
28 //遍歷Cookies
29 if(cookie != null && cookie.length > 0){
30 for (Cookie c: cookie) {
31 String name = c.getName();
32 if(name.equals("lastTime")){
33 flag = true;
34 String value = c.getValue();
35
36 //服務器響應數據
37 response.getWriter().write("<h1>歡迎回來,你上次訪問時間是<h1>"+URLDecoder.decode(value,"utf-8"));
38
39 //獲取時間,更新cookie數據
40 Date date = new Date();
41 //設置時間格式
42 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
43 value = simpleDateFormat.format(date);
44 value = URLEncoder.encode(value,"utf-8");
45 c.setValue(value);
46 //設置存活時間一個月
47 c.setMaxAge(60*60*24*30);
48 response.addCookie(c);
49
50 break;
51 }
52 }
53 }
54
55 //若沒有咱們查找的cookie
56 if (!flag ){
57 //獲取時間,更新cookie數據
58 Date date = new Date();
59 //設置時間格式
60 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:MM:SS");
61 String value = simpleDateFormat.format(date);
62 //url編碼處理特殊字符報錯問題
63 value = URLEncoder.encode(value,"utf-8");
64 Cookie cookie1 = new Cookie("lastTime",value);
65 //設置存活時間一個月
66 cookie1.setMaxAge(60*60*24*30);
67 response.addCookie(cookie1);
68
69 //設置響應內容
70 response.getWriter().write("<h1>第一次使用,存入時間爲:<h1>"+ URLDecoder.decode(value,"utf-8"));
71
72 }
73 }
74
75 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
76 this.doPost(request,response);
77
78 }
79}
概念:
原理
JSP的腳本:JSP定義Java代碼的方式
JSP的內置對象:
案例:用Jsp改造上述Cookie案例
1<%@ page import="java.net.URLDecoder" %>
2<%@ page import="java.util.Date" %>
3<%@ page import="java.text.SimpleDateFormat" %>
4<%@ page import="java.net.URLEncoder" %><%--
5 Created by IntelliJ IDEA.
6 User: Administrator
7 Date: 2020/2/26 0026
8 Time: 9:40
9 To change this template use File | Settings | File Templates.
10--%>
11<%@ page contentType="text/html;charset=UTF-8" language="java" %>
12<html>
13<head>
14 <title>顯示時間</title>
15</head>
16<body>
17
18<%
19 //定義一個標記
20 boolean flag = false;
21
22 //獲取客戶端的Cookie
23 Cookie[] cookie = request.getCookies();
24 //遍歷Cookies
25 if (cookie != null && cookie.length > 0) {
26 for (Cookie c : cookie) {
27 String name = c.getName();
28 if (name.equals("lastTime")) {
29 flag = true;
30 String value = c.getValue();
31%>//截斷
32
33<h1> 歡迎回來,你上次訪問時間是:<%= URLDecoder.decode(value, "utf-8") %></h1>
34<hr>
35<%
36 //獲取時間,更新cookie數據
37 Date date = new Date();
38 //設置時間格式
39 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
40 value = simpleDateFormat.format(date);
41 value = URLEncoder.encode(value, "utf-8");
42 c.setValue(value);
43 //設置存活時間一個月
44 c.setMaxAge(60 * 60 * 24 * 30);
45 response.addCookie(c);
46
47 break;
48 }
49 }
50 }
51
52 //若沒有咱們查找的cookie
53 if (!flag) {
54 //獲取時間,更新cookie數據
55 Date date = new Date();
56 //設置時間格式
57 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:MM:SS");
58 String value = simpleDateFormat.format(date);
59 //url編碼處理特殊字符報錯問題
60 value = URLEncoder.encode(value, "utf-8");
61 Cookie cookie1 = new Cookie("lastTime", value);
62 //設置存活時間一個月
63 cookie1.setMaxAge(60 * 60 * 24 * 30);
64 response.addCookie(cookie1);
65%>
66//設置響應內容
67<h1>第一次使用,存入時間爲:<%= URLDecoder.decode(value, "utf-8") %></h1>
68<hr>
69<%
70
71 }
72%>
73
74</body>
75</html>
76
概念:服務器端會話技術,在一次會話的屢次請求間共享數據,將數據保存在服務器端的對象中HttpSession
經常使用對象:
原理
一些細節:
問: 當客戶端關閉後,服務器不關閉,兩次獲取session是否爲同一個?
答: 默認狀況下。不是。若是須要相同,則能夠建立Cookie,鍵爲JSESSIONID,設置最大存活時間,讓cookie持久化保存。
Cookie c = new Cookie("JSESSIONID",session.getId());
c.setMaxAge(60*60);
response.addCookie(c);
問: 客戶端不關閉,服務器關閉後,兩次獲取的session是同一個嗎?
答: 不是同一個,可是要確保數據不丟失。tomcat可自動完成如下工做,但idea只能鈍化。
session的鈍化: 在服務器正常關閉以前,將session對象系列化到硬盤上(work目錄下)
session的活化: 在服務器啓動後,將session文件轉化爲內存中的session對象便可。
問: session何時被銷燬?
1. 服務器關閉時
2. session對象調用invalidate() 。
3. session默認失效時間 30分鐘
1 選擇性配置修改,在tomcat的conf目錄下的web.xml裏能夠配置
2 <session-config>
3 <session-timeout>30</session-timeout>
4 </session-config>
session的特色
1<%--
2 Created by IntelliJ IDEA.
3 User: Administrator
4 Date: 2020/2/26 0026
5 Time: 21:21
6 To change this template use File | Settings | File Templates.
7--%>
8<%@ page contentType="text/html;charset=UTF-8" language="java" %>
9<html>
10<head>
11 <title>Title</title>
12</head>
13<script>
14 //當窗口加載完以後
15 window.onload= function () {
16 //獲取驗證碼ID,當點擊事後則更換圖片
17 document.getElementById("img").onclick = function () {
18 //生成一個時間戳欺騙服務器,避免緩存加載同一張驗證碼
19 var date = new Date().getTime();
20 this.src="/test/checkCodeServlet?time="+date;
21
22 }
23
24 }
25
26</script>
27
28<%--div樣式--%>
29<style>
30 div{
31 color: red;
32 }
33</style>
34<body>
35
36<form action="/test/loginServlet" method="post">
37 <table>
38 <tr>
39 <td>用戶名</td>
40 <td><input type="text" name="username"></td>
41 </tr>
42 <tr>
43 <td>密碼</td>
44 <td><input type="password" name="password"></td>
45 </tr>
46 <tr>
47 <td>驗證碼</td>
48 <td><input type="text" name="checkCode"></td>
49 </tr>
50 <tr>
51 <td colspan="2"><img id="img" src="/test/checkCodeServlet"></td>
52 </tr>
53 <tr>
54 <td colspan="2" ><input type="submit" value="登陸"></td>
55 </tr>
56 </table>
57
58</form>
59
60<div> <%= request.getAttribute("cc_error") == null ? "" : request.getAttribute("cc_error") %></div>
61<div><%= request.getAttribute("login_error")== null ? "" : request.getAttribute("login_error")%></div>
62
63</body>
64</html>
1<%--
2 Created by IntelliJ IDEA.
3 User: Administrator
4 Date: 2020/2/26 0026
5 Time: 22:26
6 To change this template use File | Settings | File Templates.
7--%>
8<%@ page contentType="text/html;charset=UTF-8" language="java" %>
9<html>
10<head>
11 <title>Title</title>
12</head>
13<body>
14<h1> <%= request.getSession().getAttribute("user") %>歡迎你</h1>
15</body>
16</html>
1package cn.testRep.web.servlet;
2
3import javax.servlet.ServletException;
4import javax.servlet.annotation.WebServlet;
5import javax.servlet.http.HttpServlet;
6import javax.servlet.http.HttpServletRequest;
7import javax.servlet.http.HttpServletResponse;
8import javax.servlet.http.HttpSession;
9import java.io.IOException;
10
11@WebServlet("/loginServlet")
12public class LoginServlet extends HttpServlet {
13 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
14 //設置request編碼防止中文亂碼
15 request.setCharacterEncoding("utf-8");
16 //獲取參數
17 String username = request.getParameter("username");
18 String password = request.getParameter("password");
19 String checkCode = request.getParameter("checkCode");
20
21 //判斷驗證碼是否正確
22 //先獲取生成的驗證碼,須要強轉
23 String checkCode_upload = (String) request.getSession().getAttribute("checkCode");
24 //生成session對象,記錄會話過程數據
25 HttpSession session = request.getSession();
26 //獲取後,刪除session,防止內存佔用
27 session.removeAttribute("checkCode");
28 System.out.println(checkCode_upload);
29
30 if (checkCode_upload != null && checkCode_upload.equalsIgnoreCase(checkCode)) {
31 //判斷用戶名和密碼,須要調用UserDao查詢數據庫,此處省略
32 if (username.equals("admin") && password.equals("admin")) {
33 //登陸成功,存儲用戶信息
34 session.setAttribute("user", username);
35
36 //重定向地址,須要獲取虛擬目錄
37 response.sendRedirect(request.getContextPath() + "/success.jsp");
38
39 } else {
40 //登陸失敗
41 request.setAttribute("login_error", "用戶名或者密碼錯誤");
42 //轉發到登陸頁面,不須要加虛擬目錄
43 request.getRequestDispatcher("/login.jsp").forward(request, response);
44
45 }
46
47 } else {
48 //驗證碼不一致,則把提示信息存儲到requset域中,用於服務器內部轉發
49 request.setAttribute("cc_error", "驗證碼錯誤");
50 //轉發到登陸頁面,不須要加虛擬目錄
51 request.getRequestDispatcher("/login.jsp").forward(request, response);
52 }
53
54 }
55
56 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
57 this.doPost(request, response);
58 }
59}
1package cn.testRep.web.servlet;
2
3import javax.imageio.ImageIO;
4import javax.servlet.ServletException;
5import javax.servlet.annotation.WebServlet;
6import javax.servlet.http.HttpServlet;
7import javax.servlet.http.HttpServletRequest;
8import javax.servlet.http.HttpServletResponse;
9import javax.servlet.http.HttpSession;
10import java.awt.*;
11import java.awt.image.BufferedImage;
12import java.io.IOException;
13import java.util.Random;
14
15@WebServlet("/checkCodeServlet")
16public class CheckCodeServlet extends HttpServlet {
17 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18
19 int width = 100;
20 int height = 50;
21 //1.建立一個對象,在內存中畫圖
22 BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
23
24 //2.美化圖片
25 //填充背景色
26 Graphics graphics = image.getGraphics();//畫筆對象
27 graphics.setColor(new Color(200,200,169));//設置填充顏色
28 graphics.fillRect(0,0,width,height);//填充
29
30 //畫邊框
31 graphics.setColor(Color.darkGray);//設置邊框顏色
32 graphics.drawRect(0,0,width-1,height-1);//畫邊框
33
34 HttpSession session = request.getSession();
35 //用於存儲生成的驗證碼用於比對
36 StringBuilder sb = new StringBuilder();
37
38 //寫驗證碼
39 String str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
40 for (int i = 0; i < 4 ; i++) {
41 //生成隨機角標
42 Random ran = new Random();
43 int index = ran.nextInt(str.length());
44 char ch = str.charAt(index);
45 sb.append(ch); //拼接字符串
46 graphics.drawString(ch+"",width/5*(i+1),ran.nextInt(height-8)+5);
47
48 }
49 //將驗證碼存進session
50 String checkCode_session = sb.toString();
51 session.setAttribute("checkCode",checkCode_session);
52
53 //畫干擾線
54 graphics.setColor(new Color(131,175,155));
55 //隨機生成干擾線座標點
56 graphics.drawLine(20,30,10,10);
57
58 //3.輸出到頁面展現
59 ImageIO.write(image,"jpg",response.getOutputStream());
60
61
62 }
63
64 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
65 this.doPost(request,response);
66
67 }
68}