由於好久沒見的室友回來過週末,玩了兩天的王者榮耀,上了一小段。學習有點耽擱了,真的要開始減少玩的時間了。
首先我們先來介紹一下cookie和session的區別:1.Cookie是客戶端技術,程序把每個用戶的數據以cookie的形式寫給用戶各自的瀏覽器。當用戶使用瀏覽器再去訪問服務器中的web資源時,就會帶着各自的數據去。這樣,web資源處理的就是用戶各自的數據了。2.Session是服務器端技術,利用這個技術,服務器在運行時可以爲每一個用戶的瀏覽器創建一個其獨享的session對象,由於session爲用戶瀏覽器獨享,所以用戶在訪問服務器的web資源時,可以把各自的數據放在各自的session中,當用戶再去訪問服務器中的其它web資源時,其它web資源再從用戶各自的session中取出數據爲用戶服務。
一.Cookie的常用api與應用
1.常用API
response接口也中定義了一個addCookie方法,它用於在其響應頭中增加一個相應的Set-Cookie頭字段。 同樣,request接口中也定義了一個getCookies方法,它用於獲取客戶端提交的Cookie。
構造函數:public Cookie(String name,String value);
設置與得到cookie的值:setValue與getValue方法
設置與得到cookie的壽命:setMaxAge與getMaxAge方法
設置與得到cookie的有效路徑:setPath與getPath方法
設置與得到cookie的域名集:setDomain與getDomain方法
得到cookie名字:getName方法
2.應用
(1)得到上次訪問時間
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("上次訪問的時間是:");
Cookie[] cookies = request.getCookies();
for(int i=0;cookies!=null&&i<cookies.length;i++){
if(cookies[i].getName().equals("lastAccrssTime")){
Long time = Long.parseLong(cookies[i].getValue());
Date date = new Date(time);
String localDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);//toLocalString()過時了,改用這個注意月份要大M,分鐘用小M
out.write(localDate);
}
}
Cookie cookie = new Cookie("lastAccrssTime", System.currentTimeMillis()+"");
cookie.setMaxAge(1000);//設置有效時間爲1000秒
cookie.setPath("/day07/");//設置僅在/day07纔有效
response.addCookie(cookie);
}
(2)顯示用戶上次瀏覽過的商品
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//1.顯示本網站所有的書籍
out.write("本網站有以下書籍:<br/><br/>");
Map<String,Book> books = DB.getAll();
for(Map.Entry<String,Book> me : books.entrySet()){
Book book = me.getValue();
out.write("<a href='/day07/servlet/CookieDemo3?id="+book.getId()+"'target='_blank'>"+book.getName()+"</a>");
out.write("<br/>");
}
out.write("<br/>");
//2.顯示看過的書籍
Cookie[] cookies = request.getCookies();
for(int i=0;cookies!=null&&i<cookies.length;i++){
if(cookies[i].getName().equals("bookHistory")){
String[] ids = cookies[i].getValue().split("_");
for(String id:ids){
Book book = (Book) DB.getAll().get(id);
out.write(book.getName() + "<br/>");
}
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//模擬數據庫
class DB
{
private static Map<String,Book> map = new LinkedHashMap();
static{
map.put("1", new Book("1","javaweb開發","老張","一本好書"));
map.put("2", new Book("2","spring開發","老黎","一本好書"));
map.put("3", new Book("3","hibernate開發","老佟","一本好書"));
map.put("4", new Book("4","struts開發","老畢","一本好書"));
map.put("5", new Book("5","ajax開發","老張","一本好書"));
}
public static Map getAll(){
return map;
}
}
//book類
class Book{
private String id;
private String name;
private String author;
private String description;
public Book() {
super();
// TODO Auto-generated constructor stub
}
public Book(String id, String name, String author, String description) {
super();
this.id = id;
this.name = name;
this.author = author;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String bookId = request.getParameter("id");
Book book = (Book) DB.getAll().get(bookId);
//回送所有書的信息
out.write("您要查看的書的詳細信息如下:<br/><br/>");
out.write(book.getId() + "<br/>");
out.write(book.getName() + "<br/>");
out.write(book.getAuthor() + "<br/>");
out.write(book.getDescription() + "<br/>");
//2.給用戶回送包含當前商品id的cookie
String bookHistory = makeHistory(request,bookId); // 3_2
Cookie cookie = new Cookie("bookHistory",bookHistory);
cookie.setMaxAge(1*30*24*3600);
response.addCookie(cookie);
}
//注意參數
private String makeHistory(HttpServletRequest request, String bookId) {
// TODO Auto-generated method stub
String bookHistory = null;
Cookie cookies[] = request.getCookies();
for(int i=0;cookies!=null&&i<cookies.length;i++){
if(cookies[i].getName().equals("bookHistory")){
bookHistory = cookies[i].getValue();
}
}
// bookHistory=null 1 bookHistory=1
if(bookHistory==null){
return bookId;
}
//如果bookHistory不爲空,則分爲三種情況,分割字符串,放進新集合操作
List l = Arrays.asList(bookHistory.split("\\_")); //[3,4] //數組 鏈接使用"\\"的原因是規避_有特殊含義
LinkedList<String> list = new LinkedList();
list.addAll(l);
//書被瀏覽過,從原來的集合中移除,放到第一位
if(list.contains(bookId)){
list.remove(bookId);
list.addFirst(bookId);
}else {
//如果沒有被瀏覽過,且集合中已有3個(自己設置的最大顯示數),移除最後一個放到第一位
if(list.size()>=3){
list.removeLast();
list.addFirst(bookId);
}else{
//放到第一位就完事了
list.addFirst(bookId);
}
}
StringBuffer sb = new StringBuffer();
for(String lid : list){
sb.append(lid+"_");
}
return sb.deleteCharAt(sb.length()-1).toString();
}
(3)cookie細節(傳智視頻總結)
1.一個Cookie只能標識一種信息,它至少含有一個標識該信息的名稱(NAME)和設置值(VALUE)。
2.一個WEB站點可以給一個WEB瀏覽器發送多個Cookie,一個WEB瀏覽器也可以存儲多個WEB站點提供的Cookie。
3.瀏覽器一般只允許存放300個Cookie,每個站點最多存放20個Cookie,每個Cookie的大小限制爲4KB。
4.如果創建了一個cookie,並將他發送到瀏覽器,默認情況下它是一個會話級別的cookie(即存儲在瀏覽器的內存中),用戶退出瀏覽器之後即被刪除。若希望瀏覽器將該cookie存儲在磁盤上,則需要使用maxAge,並給出一個以秒爲單位的時間。將最大時效設爲0則是命令瀏覽器刪除該cookie。
5.刪除cookie時,path必須一致,否則不會刪除
2.Session
在WEB開發中,服務器可以爲每個用戶瀏覽器創建一個會話對象(session對象),注意:一個瀏覽器獨佔一個session對象(默認情況下)。因此,在需要保存用戶數據時,服務器程序可以把用戶數據寫到用戶瀏覽器獨佔的session中,當用戶使用瀏覽器訪問其它程序時,其它程序可以從用戶的session中取出該用戶的數據,爲用戶服務。
Session和Cookie的主要區別在於:
Cookie是把用戶的數據寫給用戶的瀏覽器。
Session技術把用戶的數據寫到用戶獨佔的session中。
Session對象由服務器創建,開發人員可以調用request對象的getSession方法得到session對象。
禁用Cookie後servlet共享數據導致的問題。
解決方案:URL重寫
response. encodeRedirectURL(java.lang.String url)
用於對sendRedirect方法後的url地址進行重寫。
response. encodeURL(java.lang.String url)
用於對錶單action和超鏈接的url地址進行重寫