java中的Cookie是什么_第74节:Java中的Cookie和Session
第74節(jié):第74節(jié):Java中的Cookie和Session
ServletContext:
什么是ServletContext,有什么用哦,怎么用呢?
啟動(dòng)服務(wù)器后,會(huì)給每個(gè)應(yīng)用程序創(chuàng)建一個(gè)ServletContext,并且這個(gè)ServletContext對(duì)象只有一個(gè)。可以用于獲取全局參數(shù),工程下的資源,和存取數(shù)據(jù),共享數(shù)據(jù)。
例子,如何獲取全局參數(shù),如何獲取工程下的資源,如何進(jìn)行存取數(shù)據(jù),用例子代碼進(jìn)行展示。
getServletContext().getInitParams();和getServletConfig().getInitParams();
getServletContext().getRealPath()
getServletContext().getReasourceAsStream()
InputStream is = getClass().getClassLoader().getReasourceAsStream();
相對(duì)路徑和絕對(duì)路徑
getServletContext().setAttribute()
getServletContext().getAttribute()
獲取登錄成功次數(shù)
HttpServletRequest:
請(qǐng)求對(duì)象,用于封裝客戶端提交過(guò)來(lái)的數(shù)據(jù)或者信息。
可以獲取頭信息,提交過(guò)來(lái)的數(shù)據(jù):
`request.getParameter("name"); // dashucoding url連接拼接
中文亂碼情況
HttpServletResponse:
響應(yīng)對(duì)象,服務(wù)器要返回給客戶端的數(shù)據(jù)
跳轉(zhuǎn)頁(yè)面:
response.setStatus(302);
response.setHeader("Location","success.html");
文件下載:輸出流和輸入流的對(duì)接
下載中文名字的資源:
// index.html
Insert title here默認(rèn)servlet去下載
aa.jpg
bb.txt
cc.rar
手動(dòng)下載
aa.jpg
bb.txt
cc.rar
達(dá)叔.png
// Demo01.java
package com.dashucoding.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 獲取要下載的文件名字
String fileName = request.getParameter("filename");
// 獲取這個(gè)文件在tomcat里面的絕對(duì)路徑地址
String path = getServletContext().getRealPath("download/"+fileName);
// 用于用戶下載
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
// 轉(zhuǎn)化成輸入流
InputStream is = new FileInputStream(path);
OutputStream os = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while( (len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.close();
is.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
瀏覽器
// Demo01.java
package com.dashucoding.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 獲取要下載的文件名字
String fileName = request.getParameter("filename");
// get請(qǐng)求有中文
//byte[] bytes = fileName.getBytes("ISO-8859-1");
//new String(bytes, "UTF-8");
fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
System.out.println("fileName="+fileName);
// 獲取這個(gè)文件在tomcat里面的絕對(duì)路徑地址
String path = getServletContext().getRealPath("download/"+fileName);
// 對(duì)中文的名字進(jìn)行編碼處理
// 獲取來(lái)訪客戶端的類型
String clientType = request.getHeader("User-Agent");
if (clientType.contains("Firefox")) {
fileName = DownLoadUtil.base64EncodeFileName(fileName);
}else {
fileName = URLEncoder.encode(fileName, "UTF-8");
}
// 用于用戶下載
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
// 轉(zhuǎn)化成輸入流
InputStream is = new FileInputStream(path);
OutputStream os = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while( (len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.close();
is.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
// DownLoadUtil
package com.dashucoding.servlet;
import java.io.UnsupportedEncodingException;
import sun.misc.BASE64Encoder;
public class DownLoadUtil {
public static String base64EncodeFileName(String fileName) {
BASE64Encoder base64Encoder = new BASE64Encoder();
try {
return "=?UTF-8?B?"
+ new String(base64Encoder.encode(fileName
.getBytes("UTF-8"))) + "?=";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
登錄
// LoginServlet
package com.dashucoding.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// public void setContextType(String type)
// 設(shè)置將發(fā)送到客戶端的響應(yīng)的內(nèi)容類型,如果該響應(yīng)尚未提交,給定內(nèi)容類型可能包含字符編碼規(guī)范,例如
// text/html;charseet=UTF-8,如果在調(diào)用 getWriter之前調(diào)用此方法,則只根據(jù)給定內(nèi)容類型設(shè)置響應(yīng)的字符編碼
response.setContentType("text/html;charset=utf-8");
String userName = request.getParameter("username");
String password = request.getParameter("password");
if("admin".equals(userName) && "123".equals(password)) {
response.getWriter().write("登錄成功");
}else {
response.getWriter().write("登錄失敗");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
// web
RequestRedirctionDemo
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
LoginServlet
LoginServlet
com.dashucoding.servlet.LoginServlet
LoginServlet
/login
// login
Insert title here賬號(hào):
密碼:
// LoginServlet
package com.dashucoding.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// public void setContextType(String type)
// 設(shè)置將發(fā)送到客戶端的響應(yīng)的內(nèi)容類型,如果該響應(yīng)尚未提交,給定內(nèi)容類型可能包含字符編碼規(guī)范,例如
// text/html;charseet=UTF-8,如果在調(diào)用 getWriter之前調(diào)用此方法,則只根據(jù)給定內(nèi)容類型設(shè)置響應(yīng)的字符編碼
response.setContentType("text/html;charset=utf-8");
String userName = request.getParameter("username");
String password = request.getParameter("password");
if("admin".equals(userName) && "123".equals(password)) {
// response.getWriter().write("登錄成功");
response.setStatus(302);
response.setHeader("Location", "login_success.html");
}else {
response.getWriter().write("登錄失敗");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Insert title here登錄成功!!!
重定向
package com.dashucoding.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// public void setContextType(String type)
// 設(shè)置將發(fā)送到客戶端的響應(yīng)的內(nèi)容類型,如果該響應(yīng)尚未提交,給定內(nèi)容類型可能包含字符編碼規(guī)范,例如
// text/html;charseet=UTF-8,如果在調(diào)用 getWriter之前調(diào)用此方法,則只根據(jù)給定內(nèi)容類型設(shè)置響應(yīng)的字符編碼
response.setContentType("text/html;charset=utf-8");
String userName = request.getParameter("username");
String password = request.getParameter("password");
if("admin".equals(userName) && "123".equals(password)) {
// response.getWriter().write("登錄成功");
/*response.setStatus(302);
response.setHeader("Location", "login_success.html");*/
// 重定向?qū)懛?重新定位方向
// response.sendRedirect("login_success.html");
// 請(qǐng)求轉(zhuǎn)發(fā)的寫(xiě)法
request.getRequestDispatcher("login_success.html").forward(request, response);
}else {
response.getWriter().write("登錄失敗");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Cookie
用于自動(dòng)登錄,瀏覽記錄等,是服務(wù)器給客戶端的.
Cookie cookie = new Cookie("a","b");
// 響應(yīng)
response.addCookie(cookie);
獲取Cookie
package com.dashucoding.servlet;
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;
/**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Cookie的簡(jiǎn)單使用。
//cookie 發(fā)送給客戶端,并且保存在客戶端上的一份小數(shù)據(jù)
response.setContentType("text/html;charset=utf-8");
//發(fā)送cookie給客戶端
Cookie cookie = new Cookie("aa", "bb");
//給響應(yīng),添加一個(gè)cookie
response.addCookie(cookie);
response.getWriter().write("請(qǐng)求成功了...");
//獲取客戶端帶過(guò)來(lái)的cookie
Cookie[] cookies = request.getCookies();
if(cookies != null){
for (Cookie c : cookies) {
String cookieName = c.getName();
String cookieValue = c.getValue();
System.out.println(cookieName + " = "+ cookieValue);
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Cookie是一份小數(shù)據(jù),是服務(wù)器給客戶端,存儲(chǔ)在客戶端上的一份小數(shù)據(jù).
http請(qǐng)求是無(wú)狀態(tài)的.
在響應(yīng)的時(shí)候添加Cookie
Cookie cookie = new Cookie("name", "value");
// 添加cookie
response.addCookie(cookie);
在客戶端信息里,響應(yīng)頭中多了Set-Cookie
獲取客戶端帶來(lái)的Cookie
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie c : cookies){
String cookieName = c.getName();
String cookieValue = c.getValue();
System.out.println(cookieName + " = " + cookieValue);
}
}
cookie過(guò)期
public int getMaxAge()
返回以秒為單位指定的cookie的最大生存時(shí)間.
public void setMaxAge(int expiry)
設(shè)置cookie的最大生存時(shí)間,以秒為單位.
如何顯示上次登錄時(shí)間
可以進(jìn)行判斷賬號(hào)密碼,如果上次有登錄過(guò),那么顯示上次的登錄時(shí)間.這里分兩種情況,獲取帶過(guò)來(lái)的cookie進(jìn)行判斷,第一種是沒(méi)有cookie的,第一次登錄,輸出登錄成功或者失敗,然后給客戶端添加cookie,new Cookie(),第二種的登錄過(guò)的,還是要輸出登錄成功或者是失敗,獲取以前的cookie.時(shí)間戳要重置怎么理解?
package com.dashucoding.servlet;
import java.io.IOException;
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;
import com.dashucoding.util.CookieUtil;
/**
* Servlet implementation class Demo03
*/
public class Demo03 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String userName = request.getParameter("username");
String password = request.getParameter("password");
if("admin".equals(userName) && "123".equals(password)){
//獲取cookie last-name --- >
Cookie [] cookies = request.getCookies();
//從數(shù)組里面找出我們想要的cookie
Cookie cookie = CookieUtil.findCookie(cookies, "last");
//是第一次登錄,沒(méi)有cookie
if(cookie == null){
Cookie c = new Cookie("last", System.currentTimeMillis()+"");
c.setMaxAge(60*60); //一個(gè)小時(shí)
response.addCookie(c);
response.getWriter().write("歡迎您, "+userName);
}else{
//1. 去以前的cookie第二次登錄,有cookie
long lastVisitTime = Long.parseLong(cookie.getValue());
//2. 輸出到界面,
response.getWriter().write("歡迎您, "+userName +",上次來(lái)訪時(shí)間是:"+new Date(lastVisitTime));
//3. 重置登錄的時(shí)間
cookie.setValue(System.currentTimeMillis()+"");
response.addCookie(cookie);
}
}else{
response.getWriter().write("登陸失敗 ");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
如何顯示商品瀏覽記錄
獲取提交過(guò)來(lái)的id,把id放入到cookie里,跳轉(zhuǎn)界面.
servlet?id=1;
servlet?id=2;
獲取cookie 1
1#2
setValue("1#2");
jsp
// index.jsp
pageEncoding="ISO-8859-1"%>
Insert title here
---------1------------
---------2------------
---------3------------
瀏覽記錄
package com.dashucoding.util;
import javax.servlet.http.Cookie;
public class CookieUtil {
/**
* 從一個(gè)cookie數(shù)組中找到具體我們想要的cookie對(duì)象
* @param cookies
* @param name
* @return
*/
public static Cookie findCookie(Cookie[] cookies , String name){
if(cookies != null){
for (Cookie cookie : cookies) {
if(name.equals(cookie.getName())){
return cookie;
}
}
}
return null;
}
}
Cookie[] cookies = request.getCookies();
Cookie cookie = CookieUtil.findCookie(cookies, "history");
// 如果cookie是空,表明沒(méi)有瀏覽商品
if(cookie == null){
%>
您還沒(méi)有瀏覽任何商品!
}else{
// 不是空,表明有瀏覽記錄
String[] ids = cookie.getValue().split("#");
for(String id : ids){
%>
}
}
%>
package com.dashucoding.servlet;
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 com.dashucoding.util.CookieUtil;
public class ProductInfoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
Cookie[] cookies = request.getCookies();
Cookie cookie = CookieUtil.findCookie(cookies, "history");
if (cookie==null) {
Cookie cook = new Cookie("history", id);
cook.setMaxAge(60*60*24*7);
response.addCookie(cook);
}else{
String id2 = cookie.getValue();
cookie.setValue(id+"#"+id2);
cookie.setMaxAge(60*60*24*7);
response.addCookie(cookie);
}
response.sendRedirect("product_info.htm");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
清除瀏覽記錄
清除cookie
package com.dashucoding.servlet;
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;
/**
* Servlet implementation class ClearHistory
*/
public class ClearHistory extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 清除cookie
Cookie c = new Cookie("history", "");
c.setMaxAge(0);
//c.setPath("/demo1");
response.addCookie(c);
response.sendRedirect("product_list.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
獲取cookie,添加cookie
request.getCookie();
response.addCookie();
Cookie分類
cookie.setMaxAge(0); // 刪除
cookie.setMaxAge(100); // 100秒
Cloneable
創(chuàng)建一個(gè)cookie,cookie是servlet發(fā)送到web瀏覽器中的少量信息,這些信息是由瀏覽器保存,然后發(fā)送回到服務(wù)器中.
cookie的值是唯一標(biāo)識(shí)客戶端的,可以用于cookie會(huì)話管理.一個(gè)cookie擁有一個(gè)名,值,可以有一些可選屬性.但又cookie也存在一些問(wèn)題.瀏覽器支持每個(gè)web服務(wù)器又20個(gè)cookie,共有300個(gè)cookie,每個(gè)限制在4KB.
安全隱患,大小與個(gè)數(shù)限制.
Session
會(huì)話,Session是基于Cookie的一種會(huì)話機(jī)制.Cookie是服務(wù)器返回一部分小數(shù)據(jù)在客戶端,存放在客戶端上.
Session是把數(shù)據(jù)存放在服務(wù)端.
interface httpsession
public interface httpSession
常用的方法
package com.dashucoding.servlet;
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;
/**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
// 得到會(huì)話ID
session.getId();
// 存值
session.setAttribute(name, value);
// 取值
session.getAttribute(name);
// 移植
session.removeAttribute(name);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
// web.xml
SessionDemo02
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
LoginServlet
LoginServlet
com.dashucoding.servlet.LoginServlet
LoginServlet
/login
// LoginServlet
package com.dashucoding.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("收到請(qǐng)求了");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
// login.jsp
pageEncoding="UTF-8"%>
Insert title here賬號(hào):
密碼:
session創(chuàng)建與銷毀
創(chuàng)建 request.getSession();
銷毀 Redis session 存放在服務(wù)器內(nèi)存中的數(shù)據(jù)
session關(guān)閉服務(wù)器銷毀
session會(huì)話時(shí)間過(guò)期
// 可以改的 conf\web.xml 有效期30分鐘
30
package com.dashucoding.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
String sessionid = request.getSession().getId();
System.out.println("sessionid="+sessionid);
// cookid id -> sessionid
response.getWriter().write("收到請(qǐng)求了");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
session分析
商品列表添加商品,點(diǎn)擊商品添加到購(gòu)物車,到servlet.
獲取點(diǎn)擊商品標(biāo)識(shí)id,存儲(chǔ)到購(gòu)物車,跳轉(zhuǎn)界面.
判斷購(gòu)物車是否有商品,有數(shù)量加1,沒(méi)有數(shù)量等于1.
購(gòu)物車
package com.dashucoding.servlet;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CarServlet
*/
public class CarServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
// 獲取添加到購(gòu)物車的商品id
int id = Integer.parseInt(request.getParameter("id"));
// cat dog big pig
String [] names = {"cat","dog","big","pig"};
// 取到id對(duì)應(yīng)商品
String name = names[id];
// 獲取購(gòu)物車存放東西的session
// 把一個(gè)map 對(duì)象存放到session里面去,保證只有一次
Map map = (Map) request.getSession().getAttribute("cat");
if(map == null) {
// value -> map
map = new LinkedHashMap();
request.getSession().setAttribute("cat", map);
}
// 判斷購(gòu)物車?yán)镉袥](méi)有該商品
if(map.containsKey(name)) {
// 在原來(lái)基礎(chǔ)上 +1
map.put(name, map.get(name)+1);
}else {
map.put(name, 1);
}
response.getWriter().write("
繼續(xù)購(gòu)物
");response.getWriter().write("
去購(gòu)物車結(jié)算
");}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
pageEncoding="UTF-8"%>
Insert title herecat
dog
big
pig
// cart.jsp
pageEncoding="UTF-8"%>
Insert title here您的購(gòu)物車商品如下:
// 獲取到map
Map map = (Map)session.getAttribute("cat");
// 遍歷
if(map != null){
for(String key : map.keySet()){
int value = map.get(key);
// key:商品名稱 value:商品名稱
//
名稱: 數(shù)量:
%>
名稱: 數(shù)量:
}
}
%>
package com.dashucoding.servlet;
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;
/**
* Servlet implementation class ClearCartServlet
*/
public class ClearCartServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
// cat購(gòu)物車
session.removeAttribute("cat");
response.sendRedirect("cart.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
pageEncoding="UTF-8"%>
Insert title here您的購(gòu)物車商品如下:
// 獲取到map
Map map = (Map)session.getAttribute("cat");
// 遍歷
if(map != null){
for(String key : map.keySet()){
int value = map.get(key);
// key:商品名稱 value:商品名稱
//
名稱: 數(shù)量:
%>
名稱: 數(shù)量:
}
}
%>
清空購(gòu)物車
public void invalidate()
使用,會(huì)話無(wú)效,取消對(duì)任何綁定到它的對(duì)象.
// 強(qiáng)制干掉會(huì)話
// session.invalidate();
小結(jié)
cookie和session
Cookie
獲取上一次訪問(wèn)時(shí)間,獲取瀏覽記錄,數(shù)據(jù)存放在客戶端
Session
會(huì)話技術(shù),數(shù)據(jù)存放在服務(wù)端
setAttribute 存放數(shù)據(jù)
getAttribute 取數(shù)據(jù)
removeAttribute 移除
getSessionId() 獲取會(huì)話id
invalidate() 讓會(huì)話失效
response.addCookie(new Cookie())
request.getSession 創(chuàng)建
如果看了覺(jué)得不錯(cuò)
點(diǎn)贊!轉(zhuǎn)發(fā)!
達(dá)叔小生:往后余生,唯獨(dú)有你
You and me, we are family !
90后帥氣小伙,良好的開(kāi)發(fā)習(xí)慣;獨(dú)立思考的能力;主動(dòng)并且善于溝通
簡(jiǎn)書(shū)博客: 達(dá)叔小生
https://www.jianshu.com/u/c785ece603d1
結(jié)語(yǔ)
下面我將繼續(xù)對(duì) 其他知識(shí) 深入講解 ,有興趣可以繼續(xù)關(guān)注
小禮物走一走 or 點(diǎn)贊
總結(jié)
以上是生活随笔為你收集整理的java中的Cookie是什么_第74节:Java中的Cookie和Session的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 键盘按下某键 停止运行java_实现按下
- 下一篇: linux mysql进阶_mysql进