1. 程式人生 > >servlet-cookie和session應用示例:模擬購物車

servlet-cookie和session應用示例:模擬購物車

思路分析:
1. 根據需求抽象出業務物件
User{
usrename;
password;
}


ShoppingCarItem{
product;
num;
}

ShoppingCar{
List<ShoppingCarItem>
}

2. 寫Servlet處理請求
...


domain:
Java程式碼 複製程式碼 收藏程式碼
  1. package cn.itcast.cd.domain;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.UUID;
  5. publicclass ShoppingCar {
  6. private List<ShoppingCarItem> list =
    new ArrayList<ShoppingCarItem>();
  7. /**
  8. * 根據貨品和數量往購物車中新增
  9. * @param product
  10. * @param num
  11. */
  12. publicvoid add(String product,Integer num){
  13. ShoppingCarItem carItem = new ShoppingCarItem();
  14. carItem.setNum(num);
  15. carItem.setProduct(product);
  16. carItem.setId(UUID.randomUUID().toString());
  17. list.add(carItem);
  18. }
  19. /**
  20. * 根據唯一的標示刪除購物車中對應的明細
  21. * @param id
  22. */
  23. publicvoid remove(String id){
  24. for (ShoppingCarItem item : list) {
  25. if(id.equals(item.getId())){
  26. list.remove(item);
  27. break;
  28. }
  29. }
  30. }
  31. public List<ShoppingCarItem> getList() {
  32. return list;
  33. }
  34. }
  35. package cn.itcast.cd.domain;
  36. publicclass ShoppingCarItem {
  37. private String product;
  38. private Integer num;
  39. private String id; //給每一個明細生成一個唯一的id
  40. public String getProduct() {
  41. return product;
  42. }
  43. publicvoid setProduct(String product) {
  44. this.product = product;
  45. }
  46. public Integer getNum() {
  47. return num;
  48. }
  49. publicvoid setNum(Integer num) {
  50. this.num = num;
  51. }
  52. public String getId() {
  53. return id;
  54. }
  55. publicvoid setId(String id) {
  56. this.id = id;
  57. }
  58. }
  59. package cn.itcast.cd.domain;
  60. publicclass User {
  61. private String username;
  62. private String password;
  63. public String getUsername() {
  64. return username;
  65. }
  66. publicvoid setUsername(String username) {
  67. this.username = username;
  68. }
  69. public String getPassword() {
  70. return password;
  71. }
  72. publicvoid setPassword(String password) {
  73. this.password = password;
  74. }
  75. }
package cn.itcast.cd.domain;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ShoppingCar {
	private List<ShoppingCarItem> list = new ArrayList<ShoppingCarItem>();
	
	/**
	 * 根據貨品和數量往購物車中新增
	 * @param product
	 * @param num
	 */
	public void add(String product,Integer num){
		ShoppingCarItem carItem = new ShoppingCarItem();
		carItem.setNum(num);
		carItem.setProduct(product);
		carItem.setId(UUID.randomUUID().toString());
		list.add(carItem);
	}
	
	/**
	 * 根據唯一的標示刪除購物車中對應的明細
	 * @param id
	 */
	public void remove(String id){
		for (ShoppingCarItem item : list) {
			 if(id.equals(item.getId())){
				 list.remove(item);
				 break;
			 }
		}
	}	
	
	public List<ShoppingCarItem> getList() {
		return list;
	}
	
}

package cn.itcast.cd.domain;

public class ShoppingCarItem {
	private String product;
	private Integer  num;
	private String id;  //給每一個明細生成一個唯一的id
	public String getProduct() {
		return product;
	}
	public void setProduct(String product) {
		this.product = product;
	}
	public Integer getNum() {
		return num;
	}
	public void setNum(Integer num) {
		this.num = num;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	
}

package cn.itcast.cd.domain;

public class User {
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}



servlet:

Java程式碼 複製程式碼 收藏程式碼
  1. package cn.itcast.cd.servlet;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import javax.servlet.http.HttpSession;
  9. import cn.itcast.cd.domain.ShoppingCar;
  10. publicclass BuyServlet extends HttpServlet {
  11. @Override
  12. protectedvoid service(HttpServletRequest request, HttpServletResponse response)
  13. throws ServletException, IOException {
  14. request.setCharacterEncoding("UTF-8");
  15. response.setContentType("text/html;charset=utf-8");
  16. //1. 獲取請求中的引數.
  17. String product = request.getParameter("product");
  18. String num = request.getParameter("num");
  19. //2. 獲取到購物車
  20. //2.1 首先要到session中找一下是否已經有了購物車. 如果有的話就不需要建立了... 直接把貨品放到購物車中就可以了
  21. HttpSession httpSession = request.getSession();
  22. ShoppingCar shoppingCar = (ShoppingCar)httpSession.getAttribute("SHOPINGCAR_IN_SESSION");
  23. if(shoppingCar==null){ //說明是第一次購物. 還沒有購物車的
  24. //2.2 如果從session中沒有找到購物車. 需要新建立一個購物車並且放到session中.為了下次購物使用這個購物車
  25. shoppingCar = new ShoppingCar();
  26. httpSession.setAttribute("SHOPINGCAR_IN_SESSION", shoppingCar);
  27. }
  28. shoppingCar.add(product, Integer.parseInt(num));
  29. PrintWriter pw = response.getWriter();
  30. pw.println("新增成功<br/>");
  31. pw.println("<a href='/buy.html'>繼續購物</a><br/>");
  32. pw.println("<a href='/list'>管理購物</a><br/>");
  33. }
  34. }
  35. package cn.itcast.cd.servlet;
  36. import java.io.IOException;
  37. import java.io.PrintWriter;
  38. import javax.servlet.ServletException;
  39. import javax.servlet.http.HttpServlet;
  40. import javax.servlet.http.HttpServletRequest;
  41. import javax.servlet.http.HttpServletResponse;
  42. import javax.servlet.http.HttpSession;
  43. import cn.itcast.cd.domain.ShoppingCar;
  44. import cn.itcast.cd.domain.ShoppingCarItem;
  45. import cn.itcast.cd.domain.User;
  46. publicclass ListServlet extends HttpServlet {
  47. @Override
  48. protectedvoid service(HttpServletRequest request, HttpServletResponse response)
  49. throws ServletException, IOException {
  50. request.setCharacterEncoding("UTF-8");
  51. response.setContentType("text/html;charset=utf-8");
  52. HttpSession httpSession = request.getSession();
  53. //1. 先獲取session中的User
  54. User user = (User) httpSession.getAttribute("USER_IN_SESSION");
  55. PrintWriter pw = response.getWriter();
  56. pw.println("當前使用者為:"+user.getUsername()+"<br/>");
  57. //2. 獲取session的購物車
  58. ShoppingCar shoppingCar = (ShoppingCar) httpSession.getAttribute("SHOPINGCAR_IN_SESSION");
  59. //2.1 如果在session中購物車的話,列出購物車中的明細
  60. if(shoppingCar!=null){
  61. for (ShoppingCarItem item : shoppingCar.getList()) {
  62. pw.println("貨品:"+item.getProduct()+" 數量:"+item.getNum()+"<br/>");
  63. }
  64. }else{
  65. //2.2 在session中沒有購物車的話.提示使用者沒有當前使用者名稱購物車
  66. pw.println("當前使用者沒有購物車.");
  67. }
  68. }
  69. }
  70. package cn.itcast.cd.servlet;
  71. import java.io.IOException;
  72. import java.io.PrintWriter;
  73. import javax.servlet.ServletException;
  74. import javax.servlet.http.HttpServlet;
  75. import javax.servlet.http.HttpServletRequest;
  76. import javax.servlet.http.HttpServletResponse;
  77. import javax.servlet.http.HttpSession;
  78. import cn.itcast.cd.domain.User;
  79. publicclass LoginServlet extends HttpServlet {
  80. @Override
  81. protectedvoid service(HttpServletRequest request, HttpServletResponse response)
  82. throws ServletException, IOException {
  83. request.setCharacterEncoding("UTF-8");
  84. response.setContentType("text/html;charset=utf-8");
  85. //1. 接收請求中的資料封裝物件
  86. String username = request.getParameter("username");
  87. String password = request.getParameter("password");
  88. User user = new User();
  89. user.setPassword(password);
  90. user.setUsername(username);
  91. //2. 將使用者方到session中供ListServlet從session中訪問到User
  92. HttpSession httpSession = request.getSession();
  93. httpSession.setAttribute("USER_IN_SESSION", user);
  94. PrintWriter pw = response.getWriter();
  95. pw.println("歡迎:"+username+"<br/>");
  96. pw.println("<a href='/buy.html'>購物</a><br/>");
  97. pw.println("<a href='/list'>管理購物</a><br/>");
  98. }
  99. }
package cn.itcast.cd.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.itcast.cd.domain.ShoppingCar;

public class BuyServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
	 //1.  獲取請求中的引數.
		String product = request.getParameter("product");
		String num	 = request.getParameter("num");
     //2. 獲取到購物車
		   //2.1  首先要到session中找一下是否已經有了購物車. 如果有的話就不需要建立了... 直接把貨品放到購物車中就可以了
			HttpSession httpSession = request.getSession();
			ShoppingCar shoppingCar = (ShoppingCar)httpSession.getAttribute("SHOPINGCAR_IN_SESSION");
			if(shoppingCar==null){ //說明是第一次購物. 還沒有購物車的
				//2.2  如果從session中沒有找到購物車. 需要新建立一個購物車並且放到session中.為了下次購物使用這個購物車
				shoppingCar = new ShoppingCar();
				httpSession.setAttribute("SHOPINGCAR_IN_SESSION", shoppingCar);
			}
			shoppingCar.add(product, Integer.parseInt(num));
			PrintWriter pw = response.getWriter();
			pw.println("新增成功<br/>");
			pw.println("<a href='/buy.html'>繼續購物</a><br/>");
			pw.println("<a href='/list'>管理購物</a><br/>");
		
	}
}

package cn.itcast.cd.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.itcast.cd.domain.ShoppingCar;
import cn.itcast.cd.domain.ShoppingCarItem;
import cn.itcast.cd.domain.User;

public class ListServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		
		HttpSession httpSession = request.getSession();
		//1. 先獲取session中的User
		 User user  = (User) httpSession.getAttribute("USER_IN_SESSION");
		 PrintWriter pw = response.getWriter();
		 pw.println("當前使用者為:"+user.getUsername()+"<br/>");
		//2. 獲取session的購物車
		 		ShoppingCar shoppingCar = (ShoppingCar) httpSession.getAttribute("SHOPINGCAR_IN_SESSION");
		      //2.1  如果在session中購物車的話,列出購物車中的明細
		 	   if(shoppingCar!=null){
		 		   for (ShoppingCarItem item : shoppingCar.getList()) {
		 			   pw.println("貨品:"+item.getProduct()+"  數量:"+item.getNum()+"<br/>");
		 		   }
		 	   }else{
		 		   //2.2 在session中沒有購物車的話.提示使用者沒有當前使用者名稱購物車
		 		    pw.println("當前使用者沒有購物車.");
		 	   }
		
		
		
	}
}

package cn.itcast.cd.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.itcast.cd.domain.User;

public class LoginServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		
		//1. 接收請求中的資料封裝物件
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = new User();
		user.setPassword(password);
		user.setUsername(username);
		
		//2. 將使用者方到session中供ListServlet從session中訪問到User
		HttpSession  httpSession = request.getSession();
		httpSession.setAttribute("USER_IN_SESSION", user);
		
		PrintWriter pw = response.getWriter();
		pw.println("歡迎:"+username+"<br/>");
		pw.println("<a href='/buy.html'>購物</a><br/>");
		pw.println("<a href='/list'>管理購物</a><br/>");
	}

	
}



使用者登入頁面:
Html程式碼 複製程式碼 收藏程式碼
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
  5. <title>使用者登入</title>
  6. </head>
  7. <body>
  8. <form action="/login"method="post">
  9. 使用者名稱:<inputtype="text"name="username"><br/>
  10. 密碼:<input type="text"name="password"><br/>
  11. <input type="submit"value="登入">
  12. </form>
  13. </body>
  14. </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用者登入</title>
</head>
<body>

<form action="/login" method="post">
	使用者名稱:<input type="text" name="username"><br/>
	密碼:<input type="text" name="password"><br/>
	<input type="submit" value="登入">
</form>
</body>
</html>



購買頁面:
Html程式碼 複製程式碼 收藏程式碼
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
  5. <title>購物貨品</title>
  6. </head>
  7. <body>
  8. <form action="/buy"method="post">
  9. 貨品:<selectname="product">
  10. <option value="滑鼠">滑鼠</option>
  11. <option value="鍵盤">鍵盤</option>
  12. <option value="記憶體">記憶體</option>
  13. <option value="顯示器">顯示器</option>
  14. </select><br/>
  15. 數量:<input type="text"name="num"><br/>
  16. <input type="submit"value="購買">
  17. </form>
  18. </body>
  19. </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>購物貨品</title>
</head>
<body>

<form action="/buy" method="post">
	貨品:<select name="product">
		<option value="滑鼠">滑鼠</option>
		<option value="鍵盤">鍵盤</option>
		<option value="記憶體">記憶體</option>
                  <option value="顯示器">顯示器</option>
	</select>  <br/>
	數量:<input type="text" name="num"><br/>
	<input type="submit" value="購買">
</form>
</body>
</html>


web.xml配置:
Xml程式碼 複製程式碼 收藏程式碼
  1. <?xml version="1.0"encoding="UTF-8"?>
  2. <web-app xmlns="http://java.sun.com/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  5. version="2.5">
  6. <servlet>
  7. <servlet-name>LoginServlet</servlet-name>
  8. <servlet-class>cn.itcast.cd.servlet.LoginServlet</servlet-class>
  9. </servlet>
  10. <servlet-mapping>
  11. <servlet-name>LoginServlet</servlet-name>
  12. <url-pattern>/login</url-pattern>
  13. </servlet-mapping>
  14. <servlet>
  15. <servlet-name>BuyServlet</servlet-name>
  16. <servlet-class>cn.itcast.cd.servlet.BuyServlet</servlet-class>
  17. </servlet>
  18. <servlet-mapping>
  19. <servlet-name>BuyServlet</servlet-name>
  20. <url-pattern>/buy</url-pattern>
  21. </servlet-mapping>
  22. <servlet>
  23. <servlet-name>ListServlet</servlet-name>
  24. <servlet-class>cn.itcast.cd.servlet.ListServlet</servlet-class>
  25. </servlet>
  26. <servlet-mapping>
  27. <servlet-name>ListServlet</servlet-name>
  28. <url-pattern>/list</url-pattern>
  29. </servlet-mapping>
  30. </web-app>