第74節:第74節:Java中的Cookie和Sessionhtml
ServletContext
:什麼是ServletContext
,有什麼用哦,怎麼用呢?java
啓動服務器後,會給每一個應用程序建立一個ServletContext
,而且這個ServletContext
對象只有一個。能夠用於獲取全局參數,工程下的資源,和存取數據,共享數據。web
例子,如何獲取全局參數,如何獲取工程下的資源,如何進行存取數據,用例子代碼進行展現。數組
getServletContext().getInitParams();
和getServletConfig().getInitParams();
瀏覽器
getServletContext().getRealPath()
getServletContext().getReasourceAsStream()
tomcat
InputStream is = getClass().getClassLoader().getReasourceAsStream();
安全
相對路徑和絕對路徑bash
getServletContext().setAttribute()
服務器
getServletContext().getAttribute()
cookie
獲取登陸成功次數
HttpServletRequest
:請求對象,用於封裝客戶端提交過來的數據或者信息。 能夠獲取頭信息,提交過來的數據: `request.getParameter("name"); // dashucoding url鏈接拼接
中文亂碼狀況
HttpServletResponse
:響應對象,服務器要返回給客戶端的數據
跳轉頁面: response.setStatus(302);
response.setHeader("Location","success.html");
文件下載:輸出流和輸入流的對接
下載中文名字的資源:
// index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
默認servlet去下載<br>
<a href="download/aa.jpg">aa.jpg</a><br>
<a href="download/bb.txt">bb.txt</a><br>
<a href="download/cc.rar">cc.rar</a><br>
<br>手動下載<br>
<a href="Demo01?filename=aa.jpg">aa.jpg</a><br>
<a href="Demo01?filename=bb.txt">bb.txt</a><br>
<a href="Demo01?filename=cc.rar">cc.rar</a><br>
<a href="Demo01?filename=達叔.png">達叔.png</a><br>
</body>
</html>
複製代碼
// 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");
// 獲取這個文件在tomcat裏面的絕對路徑地址
String path = getServletContext().getRealPath("download/"+fileName);
// 用於用戶下載
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
// 轉化成輸入流
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請求有中文
//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);
// 獲取這個文件在tomcat裏面的絕對路徑地址
String path = getServletContext().getRealPath("download/"+fileName);
// 對中文的名字進行編碼處理
// 獲取來訪客戶端的類型
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);
// 轉化成輸入流
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)
// 設置將發送到客戶端的響應的內容類型,若是該響應還沒有提交,給定內容類型可能包含字符編碼規範,例如
// text/html;charseet=UTF-8,若是在調用 getWriter以前調用此方法,則只根據給定內容類型設置響應的字符編碼
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
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RequestRedirctionDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.dashucoding.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
複製代碼
// login
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login">
帳號: <input type="text" name="username"/><br>
密碼: <input type="text" name="password"/><br>
<input type="submit" value="登陸"/><br>
</form>
</body>
</html>
複製代碼
// 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)
// 設置將發送到客戶端的響應的內容類型,若是該響應還沒有提交,給定內容類型可能包含字符編碼規範,例如
// text/html;charseet=UTF-8,若是在調用 getWriter以前調用此方法,則只根據給定內容類型設置響應的字符編碼
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);
}
}
複製代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>登陸成功!!!</h1>
</body>
</html>
複製代碼
重定向
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)
// 設置將發送到客戶端的響應的內容類型,若是該響應還沒有提交,給定內容類型可能包含字符編碼規範,例如
// text/html;charseet=UTF-8,若是在調用 getWriter以前調用此方法,則只根據給定內容類型設置響應的字符編碼
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");*/
// 重定向寫法,從新定位方向
// response.sendRedirect("login_success.html");
// 請求轉發的寫法
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
用於自動登陸,瀏覽記錄等,是服務器給客戶端的.
Cookie cookie = new Cookie("a","b");
// 響應
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的簡單使用。
//cookie 發送給客戶端,而且保存在客戶端上的一份小數據
response.setContentType("text/html;charset=utf-8");
//發送cookie給客戶端
Cookie cookie = new Cookie("aa", "bb");
//給響應,添加一個cookie
response.addCookie(cookie);
response.getWriter().write("請求成功了...");
//獲取客戶端帶過來的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
是一份小數據,是服務器給客戶端,存儲在客戶端上的一份小數據.
http
請求是無狀態的.
在響應的時候添加Cookie
Cookie cookie = new Cookie("name", "value");
// 添加cookie
response.addCookie(cookie);
複製代碼
在客戶端信息裏,響應頭中多了Set-Cookie
獲取客戶端帶來的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
過時
public int getMaxAge()
返回以秒爲單位指定的cookie
的最大生存時間.
public void setMaxAge(int expiry)
設置cookie
的最大生存時間,以秒爲單位.
如何顯示上次登陸時間
能夠進行判斷帳號密碼,若是上次有登陸過,那麼顯示上次的登陸時間.這裏分兩種狀況,獲取帶過來的cookie
進行判斷,第一種是沒有cookie
的,第一次登陸,輸出登陸成功或者失敗,而後給客戶端添加cookie
,new Cookie()
,第二種的登陸過的,仍是要輸出登陸成功或者是失敗,獲取之前的cookie
.時間戳要重置怎麼理解?
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();
//從數組裏面找出咱們想要的cookie
Cookie cookie = CookieUtil.findCookie(cookies, "last");
//是第一次登陸,沒有cookie
if(cookie == null){
Cookie c = new Cookie("last", System.currentTimeMillis()+"");
c.setMaxAge(60*60); //一個小時
response.addCookie(c);
response.getWriter().write("歡迎您, "+userName);
}else{
//1. 去之前的cookie第二次登陸,有cookie
long lastVisitTime = Long.parseLong(cookie.getValue());
//2. 輸出到界面,
response.getWriter().write("歡迎您, "+userName +",上次來訪時間是:"+new Date(lastVisitTime));
//3. 重置登陸的時間
cookie.setValue(System.currentTimeMillis()+"");
response.addCookie(cookie);
}
}else{
response.getWriter().write("登錄失敗 ");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
複製代碼
如何顯示商品瀏覽記錄
獲取提交過來的id
,把id
放入到cookie
裏,跳轉界面.
servlet?id=1;
servlet?id=2;
獲取cookie 1
1#2
setValue("1#2");
複製代碼
jsp
// index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<br>---------1------------<br>
<%! int a = 123; %>
<br>---------2------------<br>
<% int b = 123456; %>
<br>---------3------------<br>
<%=a %><br>
<%=b %>
</body>
</html>
複製代碼
瀏覽記錄
package com.dashucoding.util;
import javax.servlet.http.Cookie;
public class CookieUtil {
/**
* 從一個cookie數組中找到具體咱們想要的cookie對象
* @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是空,代表沒有瀏覽商品
if(cookie == null){
%>
<h2> 您尚未瀏覽任何商品! </h2>
<%
}else{
// 不是空,代表有瀏覽記錄
String[] ids = cookie.getValue().split("#");
for(String id : ids){
%>
<li style="width: 150px;height: 216;text-align: center;"><img src="products/1/cs1000<%=id %>.jpg" width="130px" height="130px" /></li>
<%
}
}
%>
複製代碼
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
建立一個cookie
,cookie
是servlet
發送到web
瀏覽器中的少許信息,這些信息是由瀏覽器保存,而後發送回到服務器中.
cookie
的值是惟一標識客戶端的,能夠用於cookie
會話管理.一個cookie
擁有一個名,值,能夠有一些可選屬性.但又cookie
也存在一些問題.瀏覽器支持每一個web
服務器又20個cookie
,共有300個cookie
,每一個限制在4KB.
安全隱患,大小與個數限制.
Session
會話,Session
是基於Cookie
的一種會話機制.Cookie
是服務器返回一部分小數據在客戶端,存放在客戶端上.
Session
是把數據存放在服務端.
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();
// 獲得會話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
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SessionDemo02</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.dashucoding.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
複製代碼
// 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("收到請求了");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
複製代碼
// login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login">
帳號: <input type="text" name="username"/><br>
密碼: <input type="text" name="password"/><br>
<input type="submit" value="登陸"/><br>
</form>
</body>
</html>
複製代碼
session
建立與銷燬
建立 request.getSession();
銷燬 Redis session 存放在服務器內存中的數據
session關閉服務器銷燬
session會話時間過時
複製代碼
// 能夠改的 conf\web.xml 有效期30分鐘
<session-config>
<session-timeout>30</session-timeout>
</session-config>
複製代碼
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("收到請求了");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
複製代碼
session
分析
商品列表添加商品,點擊商品添加到購物車,到servlet
.
獲取點擊商品標識id
,存儲到購物車,跳轉界面.
判斷購物車是否有商品,有數量加1,沒有數量等於1.
購物車
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");
// 獲取添加到購物車的商品id
int id = Integer.parseInt(request.getParameter("id"));
// cat dog big pig
String [] names = {"cat","dog","big","pig"};
// 取到id對應商品
String name = names[id];
// 獲取購物車存放東西的session
// 把一個map 對象存放到session裏面去,保證只有一次
Map<String, Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cat");
if(map == null) {
// value -> map
map = new LinkedHashMap<String, Integer>();
request.getSession().setAttribute("cat", map);
}
// 判斷購物車裏有沒有該商品
if(map.containsKey(name)) {
// 在原來基礎上 +1
map.put(name, map.get(name)+1);
}else {
map.put(name, 1);
}
response.getWriter().write("<a href='product_list.jsp'><h2>繼續購物</h2></a>");
response.getWriter().write("<a href='cart.jsp'><h2>去購物車結算</h2></a>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
複製代碼
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="CarServlet?id=0"><h2>cat</h2></a><br>
<a href="CarServlet?id=1"><h2>dog</h2></a><br>
<a href="CarServlet?id=2"><h2>big</h2></a><br>
<a href="CarServlet?id=3"><h2>pig</h2></a><br>
</body>
</html>
複製代碼
// cart.jsp
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
您的購物車商品以下:
<%
// 獲取到map
Map<String,Integer> map = (Map<String,Integer>)session.getAttribute("cat");
// 遍歷
if(map != null){
for(String key : map.keySet()){
int value = map.get(key);
// key:商品名稱 value:商品名稱
// <h3>名稱: 數量: </h3>
%>
<h3>名稱: <%=key %> 數量: <%=value %></h3><br>
<%
}
}
%>
</body>
</html>
複製代碼
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購物車
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);
}
}
複製代碼
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
您的購物車商品以下:
<%
// 獲取到map
Map<String,Integer> map = (Map<String,Integer>)session.getAttribute("cat");
// 遍歷
if(map != null){
for(String key : map.keySet()){
int value = map.get(key);
// key:商品名稱 value:商品名稱
// <h3>名稱: 數量: </h3>
%>
<h3>名稱: <%=key %> 數量: <%=value %></h3><br>
<%
}
}
%>
<a href="ClearCartServlet"><h4>清空購物車</h4></a>
</body>
</html>
複製代碼
public void invalidate()
使用,會話無效,取消對任何綁定到它的對象.
// 強制幹掉會話
// session.invalidate();
複製代碼
cookie和session
複製代碼
Cookie
獲取上一次訪問時間,獲取瀏覽記錄,數據存放在客戶端
Session
會話技術,數據存放在服務端
setAttribute 存放數據
getAttribute 取數據
removeAttribute 移除
getSessionId() 獲取會話id
invalidate() 讓會話失效
複製代碼
response.addCookie(new Cookie())
request.getSession 建立
複製代碼
若是看了以爲不錯
點贊!轉發!
達叔小生:日後餘生,惟獨有你 You and me, we are family ! 90後帥氣小夥,良好的開發習慣;獨立思考的能力;主動而且善於溝通 簡書博客: 達叔小生 www.jianshu.com/u/c785ece60…