6 Cookies 和Session
阿新 • • 發佈:2018-02-12
code log Coding cookie對象 ken htm cti except tex 1.HTTP協議無狀態帶來的問題
http協議在一個會話中的多個請求之間是不能共享數據的
(實際是需要在一個會話的多個請求共享數據)
會話跟蹤技術:在一個會話共享數據
2.解決一個會話中多個請求之間共享數據的三種方式
①.使用GET方式,將需要共享的數據以參數的形式傳遞給下一個頁面即可
使用GET方式共享數據,所有數據都暴露在地址欄中,不安全
②使用cookie技術
將需要共享的數據封裝到瀏覽器的請求頭中
③使用session技術
3.Cookie
客戶端技術,將需要共享的數據存放在瀏覽器中,每次請求時,對應需要共享數據的 頁面只需在瀏覽器獲取需要的數據即可。 ①創建Cookie對象共享數據 Cookie cookie=new Cookie(String name,String value); ②將cookie響應給瀏覽器 resp.addCookie(cookie); ③從請求對象獲取所有的cookie Cookie[] cookies=req.getCookies(); for(Cookie cookie:cookies){ if("currentName".equals(cookie.getName())){ String username=cookie.getValue(); } }
4.cookie中文問題的解決方案,先編碼後解碼 編碼: Cookie cookie=new Cookie("currentName",URLEncoder.encode(username,"utf-8")); 解碼: username=URLDecoder.decode(cookie.getValue(),"utf-8"); Cookie的缺陷: Cookie不能存儲中文字符 Cookie一次只能存儲單個字符串,不能存儲對象 cookie大小限制在4kb內 cookie數據是存儲在瀏覽器中的,瀏覽器把Cookie數據刪除了,那麽共享數據就找不回來了 不同Cookie下面的路徑是不同的,路徑不同的Cookie之間是不能共享數據的 解決方案: 將Cookie路徑設置項目的根路徑 cookie.setPath(“/”) @WebServlet("/cookie/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); //接受請求參數 String username = req.getParameter("username"); //================================================ //創建Cookie對象,並且共享數據 (相當辦卡的操作) Cookie cookie = new Cookie("currentName", URLEncoder.encode(username,"utf-8")); //設置Cookie的時長 單位 秒 //cookie.setMaxAge(10); //刪除Cookie //cookie.setMaxAge(0); //設置Cookie的路徑為根路徑 cookie.setPath("/"); //將Cookie數據響應給瀏覽器 (相當於將辦理好的會員卡給用戶) resp.addCookie(cookie); //創建新的Cookie ,覆蓋之前的cookie (相當於修改了cookie)
// Cookie cookie1 = new Cookie("currentName", "jinken");
// resp.addCookie(cookie1);
//================================================ PrintWriter out = resp.getWriter(); out.print("歡迎 : "+username+" <br>"); out.print("<a href=‘/ooxx/list‘>收件箱(500)</a>"); }
}
@WebServlet("/ooxx/list")
public class ListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// =============================================
String username = null;
// 從請求對象中獲取所有的cookie
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
if("currentName".equals(cookie.getName())){
username = URLDecoder.decode(cookie.getValue(), "utf-8");
break;
}
}
// =============================================
PrintWriter out = resp.getWriter();
out.print("歡迎 :"+username+" <br>");
for (int i = 0; i < 5; i++) {
out.print("<a href=‘/cookie/content‘>郵件 (" + i + ")</a><br/>");
}
}
}
@WebServlet("/cookie/content")
public class ContentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String username = null;
// =============================================
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
if("currentName".equals(cookie.getName())){
username = URLDecoder.decode(cookie.getValue(), "utf-8");
}
}
// =============================================
PrintWriter out = resp.getWriter();
out.print("歡迎 : "+username+" <br>");
out.print("班長, 你最近好嗎?");
}
}
jsp中書寫Cookies
<%
Cookie cookie = new Cookie(
URLEncoder.encode("姓名","UTF-8"),
URLEncoder.encode("李佳龍","UTF-8")
);
response.addCookie(cookie);
%>
<html>
<title>Cookie-中文</title>
<body>
<%
if(request.getCookies()!=null)
{
for(Cookie coo : request.getCookies())
{
String name =URLDecoder.decode(coo.getName(),"UTF-8");
String value = URLDecoder.decode(coo.getValue(),"UTF-8");
out.println(name "-- " value);
}
}
%>
el表達式:
${cookie}<!-- 顯示所有Cookie對象 -->
${cookie.age.name }<!-- 顯示Cookie名為age的name -->
${cookie.age.value }<!-- 顯示Cookie名為age的值 -->
4.Session
Session是服務器端技術(把識別數據/共享數據存放在服務端)
為每一個用戶的瀏覽器創建獨立的session,可以把數據存放在各自的session中,
取數據也從各自session取
(session是一個特殊的cookie,session得底層依然是cookie技術,cookie是內存地址
JSESSIONID)
1.獲取Session對象
HttpSession session=request.getSession();
如果內存中有session對象,返回,沒有則創建一個並返回
2.共享數據
setAttribute("USER_IN_SESSION",user);
3.獲取共享數據
getAttribute("USER_IN_SESSION");
當cookie被禁用後,URL重寫問題
瀏覽器禁用cookie後,就再也不能接收服務器響應的cookie,此時cookie和session
就不能共享數據,直接訪問URL地址是不能獲取共享數據的
使用URL重寫
resp.encodeURL(String url);
如果瀏覽器禁用cookie,url會自動加上jsessionid,如果沒有禁用,就不會
加上jsessionid
@WebServlet("/session/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//接受請求參數
String username = req.getParameter("username");
String password = req.getParameter("password");
User user = new User();
user.setUsername(username);
user.setPassword(password);
//================================================
//1.獲取Sesion對象
HttpSession session = req.getSession();
//2.將數據共享的Session對象中
//session.setAttribute("USERNAME_IN_SESSION", username);
session.setAttribute("USER_IN_SESSION", user);
//3.修改共享數據
//session.setAttribute("USERNAME_IN_SESSION", "虛竹");
//4.刪除session中共享的數據
//session.removeAttribute("USERNAME_IN_SESSION");
//5.清空Sesion對象中所有數據
//session.invalidate();
//6.設置當前Session10秒鐘超時
//session.setMaxInactiveInterval(10);
//獲取Session的id
String sessionId = session.getId();
System.out.println(sessionId);
//================================================
//使用url重寫
//String newUrl = resp.encodeURL(String oldUrl);
// 如果瀏覽器禁用了 Cookie,newUrl後面會自動加上 jsessionid,如果沒有禁用,就不會加上jsession
PrintWriter out = resp.getWriter();
out.print("歡迎 : "+username+" <br>");
// out.print("<a href=‘/session/list;jsessionid="+session.getId()+"‘>收件箱(500)</a>");
out.print("<a href=‘"+resp.encodeURL("/session/list")+"‘>收件箱(500)</a>");
}
}
@WebServlet("/session/list")
public class ListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// =============================================
//獲取Session對象
HttpSession session = req.getSession();
//獲取sesion共享的數據
User user = (User)session.getAttribute("USER_IN_SESSION");
System.out.println(user);
// =============================================
PrintWriter out = resp.getWriter();
out.print("歡迎 :"+user.getUsername()+" <br>");
for (int i = 0; i < 5; i++) {
//out.print("<a href=‘/session/content;jsessionid="+session.getId()+"‘>郵件 (" + i + ")</a><br/>");
out.print("<a href=‘"+resp.encodeURL("/session/content")+"‘>郵件 (" + i + ")</a><br/>");
}
}
}
@WebServlet("/session/content")
public class ContentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// =============================================
// 獲取Session對象
HttpSession session = req.getSession();
// 獲取sesion共享的數據
User user = (User) session.getAttribute("USER_IN_SESSION");
// =============================================
PrintWriter out = resp.getWriter();
out.print("歡迎 : " + user.getUsername() + " <br>");
out.print("班長, 你最近好嗎?");
}
}
6 Cookies 和Session