今日任務
Ø 顯示用戶的上次訪問時間
Ø 登錄系統以後顯示商品瀏覽記錄
Ø 購買商品將商品添加到購物車
Ø 系統登錄的驗證碼的校驗
教學導航
教學目標
瞭解JSP的簡單的使用
掌握Cookie的使用
掌握Session的使用
教學方法
案例驅動法
1.1 上次課內容回顧:
Response
- 通過response設置狀態碼:setStatus(int status);
- 通過response設置響應頭:setHeader(String name,String value);,setIntHeader(String name,int value),setDateHeader(String name,long date);
- 通過response設置響應體:getOutputStream(),getWriter();
- response的其他的API:
- sendRedirect(String path);
- response輸出中文的亂碼問題:
- 字節流輸出中文:
- 設置瀏覽器的字符集編碼. response.setHeader(“Content-Type”,”text/html;charset=UTF-8”);
- 設置輸出內容的字節數組的字符集編碼. “”.getBytes(“UTF-8”);
- 字符流輸出中文:
- 設置瀏覽器字符集編碼. response.setHeader(“Content-Type”,”text/html;charset=UTF-8”);
- 設置response的緩衝區的編碼. response.setCharacterEncoding(“UTF-8”);
- 字節流輸出中文:
- response完成了文件下載功能:
Request - 使用request獲得客戶機的信息. getRemoteAddr(),getMethod(),getRequestURI(),getRequestURL()
- 獲得請求參數:getParameter(),getParameterValues(),getParameterMap()
- 作爲域對象存取數據:setAttribute(),getAttribute(),removeAttribute();
- 接收參數的中文亂碼的處理:
- GET :new String(“”.getBytes(“ISO-8859-1”),”UTF-8”)
- POST :request.setCharacterEncoding(“UTF-8”);
- request何時創建和銷燬的?
- 創建:從客戶端向服務器發送請求.那麼服務器創建一個request對象.
- 銷燬:服務器爲這次請求作出了響應之後,服務器就會銷燬request對象.
- 作用範圍:一次請求.
- 轉發和重定向區別?
- 轉發是一次請求一次響應,重定向兩次請求和兩次響應.
- 轉發地址欄不變,重定向會變化.
- 轉發的路徑不需要加工程名,重定向需要加工程名.
- 轉發只能在本網站內部,重定向可以定向到任何網站.
1.2 案例一:記錄用戶的上次登陸訪問時間.1.2.1 需求:
用戶登錄完成後,顯示您是第x位訪問的用戶,您的上次訪問時間是:yyyy-MM-dd.
- 如果第一次訪問的話,只顯示您是第x位用戶.
- 如果不是第一次訪問的話,顯示您是第x位訪問的用戶,您的上次訪問時間是:yyyy-MM-dd.
1.2.2 分析:1.2.2.1 技術分析:
【會話技術】
Ø 什麼是會話 :用戶打開一個瀏覽器訪問頁面,訪問網站的很多頁面,訪問完成後將瀏覽器關閉的過程稱爲是一次會話.
Ø 常見的會話技術: - Cookie :將數據保存到客戶端瀏覽器.
- Session :將數據保存到服務器端.
Ø 爲什麼使用會話技術? - 私有的數據,購物信息數據保存在會話技術中.
參見圖一和圖二
Ø 使用會話技術:
【Cookie技術的使用】
Ø 向瀏覽器保存數據:
HttpServletResponse有一個方法: - void addCookie(Cookie cookie);
Ø 獲得瀏覽器帶過來的Cookie:
HttpServletRequest有一個方法: - Cookie[] getCookies();
Ø 創建一個Cookie對象: - Cookie(String name,String value);
【JSP的簡單概述】
Ø 什麼是JSP :Java Server Pages(Java服務器端頁面).JSP = Java代碼 + HTML的元素 + JSP內置東西
Ø SUN公司爲什麼推出JSP動態網頁開發技術: - SUN公司推出的Servlet技術進行動態網頁開發.發現Servlet自身有不足沒有辦法與ASP,PHP技術競爭.想在動態網頁中輸出表單.在Servlet中獲得PrintWriter out = response.getWriter();
- out.println(“<form action=’’ method=’’>”);
- out.println(“</form>”);
- SUN又推出了動態的網頁開發技術就是JSP.
Ø JSP的執行過程: - JSP會被翻譯成Servlet,編譯成class進行執行的.
Ø JSP的嵌入Java代碼:JSP的腳本元素 - <%! %> :翻譯成類中的成員部分. 定義變量,定義方法,定義類.Servlet是線程不安全的,儘量少在類中定義成員屬性!!
- <% %> :翻譯成類的service方法內部的內容. 定義變量,定義類,直接寫代碼塊.
- <%= %> :翻譯成service方法內部的out.print();
1.2.2.2 步驟分析:
【步驟一】:準備登陸的案例.
【步驟二】:在統計人數的Servlet中.判斷是否是第一次訪問.
【步驟三】:根據是否是第一次顯示不同的信息,同時將當前的時候保存到Cookie中.
1.2.3 代碼實現
public class CountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
Integer count = (Integer) this.getServletContext().getAttribute("count");
// response.getWriter().println("<h1>現在網站被訪問的次數爲:"+count+"</h1>");
/**
* 獲得瀏覽器中帶過來的所有的Cookie信息,從數組中查找有沒有指定名稱的Cookie
* 判斷用戶是否是第一次訪問:(從數組中沒有找到指定名稱的Cookie)
* * 如果是第一次:顯示歡迎,記錄當前訪問的時間存入到Cookie中.
* * 如果不是第一次:顯示歡迎,上一次訪問時間,同時記錄當前訪問的時間存入到Cookie中。
*/
// 獲得瀏覽器帶過來的所有的Cookie:
Cookie[] cookies = request.getCookies();
// 從數組中查找指定名稱的Cookie:
Cookie cookie = CookieUtils.findCookie(cookies, "lastVisit");
// 判斷是否是第一次:
if(cookie == null){
// 第一次訪問
response.getWriter().println("您是第"+count+"位訪客!");
}else{
// 不是第一次
Long l = Long.parseLong(cookie.getValue());
Date d = new Date(l);
response.getWriter().println("您是第"+count+"位訪客! 上次訪問時間是:"+d.toLocaleString());
}
// 創建一個Cookie對象:
Cookie c = new Cookie("lastVisit",""+System.currentTimeMillis());
// 保存到瀏覽器端:
response.addCookie(c);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
1.2.4 總結:1.2.4.1 Cookie的常用API:
Ø Cookie的常用的API:
- getName();
- getValue();
- setDomain(String domain); -- 設置Cookie的有效域名. // www.baidu.com music.baidu.com
- setPath(String path); -- 設置Cookie的有效路徑.
- setMaxAge(int maxAge); -- 設置Cookie的有效時間.
Ø Cookie的分類有關: - 會話級別的Cookie:默認的Cookie.關閉瀏覽器Cookie就會銷燬.
- 持久級別的Cookie:可以設置Cookie的有效時間.那麼關閉瀏覽器Cookie還會存在. 手動銷燬持久性Cookie. setMaxAge(0)---前提是有效路徑必須一致.
1.3 案例二:記錄用戶的商品瀏覽記錄:1.3.1 需求:
在購物網站上瀏覽商品的信息,商家爲了留住用戶,記住之前瀏覽的一些商品.
1.3.2 分析:1.3.2.1 技術分析:
1.3.2.2 步驟分析:
【步驟一】:在登錄完成後,顯示商品列表頁面.
【步驟二】:爲商品列表頁面做一些準備工作.
【步驟三】:點擊某個商品,將商品ID傳遞一個Servlet.
【步驟四】:在Servlet中:判斷是否是第一次瀏覽商品
【步驟五】:如果是第一次:將商品的ID存入到Cookie中即可.
【步驟六】:如果不是第一次:判斷該商品是否已經瀏覽了.
【步驟七】:如果瀏覽器過.刪除之前元素,將該元素添加到最前面.
【步驟八】:如果沒有瀏覽過該商品.判斷最大長度,沒有超過限制,直接加到最前,如果已經超過限制,刪除最後一個,將其插入到最前.
1.3.3 代碼實現:
public class ProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* * 接收商品id.
* * 接收從客戶端帶過來的所有Cookie.
* * 從Cookie的數組中查找指定名稱的Cookie.
* * 判斷是否是第一次瀏覽商品:
* * 第一次瀏覽商品
* * 直接將商品的ID存入到Cookie.
* * 將Cookie回寫到瀏覽器.
* * 不是第一次瀏覽商品 1-2
* * 判斷當前的商品是否已經在瀏覽記錄.
* * 已經存在: 2-1 移除當前元素,將當前元素添加到最開始.
* * 沒在瀏覽記錄中:
* * 判斷是否已經超過了最大長度:如果超過 2-1-3:刪除最後一個 將當前元素添加到最前面.
* * 沒有超過:直接將該元素添加到最前位置.
* * 將轉換的id的值存入到Cookie,回寫瀏覽器.
*/
// 接收id:
String id = request.getParameter("id");
// 獲得所有的Cookie的信息:
Cookie[] cookies = request.getCookies();
// 判斷是否是第一次:
Cookie cookie = CookieUtils.findCookie(cookies, "history");
if(cookie == null){
// 第一次瀏覽商品
Cookie c = new Cookie("history",id);
c.setPath("/day11");
c.setMaxAge(60*60*24*7);
response.addCookie(c);
}else{
// 不是第一次瀏覽
// 判斷選擇的商品是否已經在瀏覽記錄中 2-1
String value = cookie.getValue();
String[] ids = value.split("-");
// 將數組變爲集合:
LinkedList<String> list = new LinkedList<String>(Arrays.asList(ids));
if(list.contains(id)){
// 之前瀏覽過該商品
list.remove(id); // 1-2-3
list.addFirst(id);
}else{
// 沒有瀏覽過該商品.
if(list.size() >=3 ){
// 超過3個
list.removeLast();
list.addFirst(id);
}else{
// 沒到3個.
list.addFirst(id);
}
}
// 將list中的元素取出,使用-連接上保存到Cookie,寫回瀏覽器.
StringBuffer sb = new StringBuffer();
for(String s:list){
sb.append(s).append("-");
}
String sValue = sb.toString().substring(0,sb.length()-1);
System.out.println(sValue);
// 存入到Cookie中
Cookie c = new Cookie("history",sValue);
c.setPath("/day11");
c.setMaxAge(60*60*24*7);
response.addCookie(c);
}
request.getRequestDispatcher("/demo2/product_info.htm").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
1.3.4 總結:1.3.4.1 清空瀏覽記錄:
刪除持久性的Cookie:
public class ClearServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("history",null);
cookie.setPath("/day11");
cookie.setMaxAge(0);
response.addCookie(cookie);
response.sendRedirect("/day11/demo2/product_list.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
1.4 案例三:將商品添加到購物車:1.4.1 需求:
查看某個商品詳情的時候,添加到購物車.需要將商品添加到購物車.
1.4.2 分析:1.4.2.1 技術分析:
【Session的概述】
Cookie本身是有大小和個數的限制.Session沒有限制.Cookie的數據保存在客戶端,Session數據保存在服務器端.
Ø Session的執行原理:基於Cookie的.
Ø 使用Session:
- 獲得Session:
- request.getSession();
1.4.2.2 步驟分析:
【步驟一】:點擊加入購物車提交到Servlet
【步驟二】:在Servlet將購物的商品存入到Session中.
【步驟三】:可以創建一個Map集合用於保存購物信息Map的key可以是商品的名稱,Map的value是數量.
【步驟四】:在購物車頁面中顯示Map中的數據就可以.
1.4.3 代碼實現:
- request.getSession();
public class CartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 接收商品名稱:
String name = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");
// 創建Map集合用於保存購物信息.Map<String,Integer> Map的key是商品的名稱 value是購買的數量.
Map<String,Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart");
if(map == null){
map = new LinkedHashMap<String,Integer>();
}
// 判斷購物車中是否已經買了該商品.
if(map.containsKey(name)){
// map中已經有該商品:// * 如果購物車中已經有該商品: 獲得到Map中該商品的數量+1。 存回到Map集合中.
Integer count = map.get(name);
count++;
map.put(name, count);
}else{
// map中沒有該商品.// * 如果購物車中沒有改商品: 將商品添加到Map集合中 數量1.
map.put(name, 1);
}
// * 將Map集合保存到session中.
request.getSession().setAttribute("cart", map);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println("<h3><a href='/day11/demo2/product_list.jsp'>繼續購物</a> | <a href='/day11/demo2/cart.jsp'>去結算</a></h3>");
}
1.4.4 總結:1.4.4.1 Session是域對象:
session何時創建和銷燬?作用範圍:
- 創建:服務器端第一次調用getSession()創建session.
- 銷燬:三種情況銷燬session:
- 1.session過期. 默認過期時間爲30分鐘.
- 2.非正常關閉服務器.如果正常關閉session序列化到硬盤.
- 3.手動調用session.invalidate();
- 作用範圍:多次請求.(一次會話)
1.5 案例四:進行一次性驗證碼的校驗1.5.1 需求:
在登錄的頁面中,需要有一個驗證碼的校驗.
1.5.2 分析:1.5.2.1 技術分析:
使用session保存生產的驗證碼.
1.5.2.2 步驟分析:
【步驟一】:生成驗證碼,將生成驗證碼的隨機的4個字母或數字保存到session中.
【步驟二】:在頁面中輸入驗證碼值,點提交.
【步驟三】:在Servlet中從表單中獲得驗證碼從session中獲得一個驗證碼.
【步驟四】:比對兩個驗證碼值是否一致.
【步驟五】:將session中保存的驗證碼清空.
1.5.3 代碼實現:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 校驗驗證碼程序:
String code1 = request.getParameter("code");
String code2 = (String) request.getSession().getAttribute("code");
request.getSession().removeAttribute("code");
if(!code1.equalsIgnoreCase(code2)){
request.setAttribute("msg", "驗證碼輸入錯誤!");
request.getRequestDispatcher("/demo2/login.jsp").forward(request, response);
return ;
}
...
}
1.5.4 總結:1.5.4.1 使用JS控制圖片切換:
<script type="text/javascript">
function changeImg(){
document.getElementById("img1").src="/day11/CheckImgServlet?time="+new Date().getTime();
}
</script>