servlet-cookie和session應用示例:模擬購物車
阿新 • • 發佈:2019-01-29
思路分析:
1. 根據需求抽象出業務物件
User{
usrename;
password;
}
ShoppingCarItem{
product;
num;
}
ShoppingCar{
List<ShoppingCarItem>
}
2. 寫Servlet處理請求
...
domain:
Java程式碼
servlet:
Java程式碼
使用者登入頁面:
Html程式碼
購買頁面:
Html程式碼
web.xml配置:
Xml程式碼
1. 根據需求抽象出業務物件
User{
usrename;
password;
}
ShoppingCarItem{
product;
num;
}
ShoppingCar{
List<ShoppingCarItem>
}
2. 寫Servlet處理請求
...
domain:
Java程式碼
- package cn.itcast.cd.domain;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.UUID;
- publicclass ShoppingCar {
- private List<ShoppingCarItem> list =
- /**
- * 根據貨品和數量往購物車中新增
- * @param product
- * @param num
- */
- publicvoid 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
- */
- publicvoid 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;
- publicclass ShoppingCarItem {
- private String product;
- private Integer num;
- private String id; //給每一個明細生成一個唯一的id
- public String getProduct() {
- return product;
- }
- publicvoid setProduct(String product) {
- this.product = product;
- }
- public Integer getNum() {
- return num;
- }
- publicvoid setNum(Integer num) {
- this.num = num;
- }
- public String getId() {
- return id;
- }
- publicvoid setId(String id) {
- this.id = id;
- }
- }
- package cn.itcast.cd.domain;
- publicclass User {
- private String username;
- private String password;
- public String getUsername() {
- return username;
- }
- publicvoid setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- publicvoid setPassword(String password) {
- this.password = password;
- }
- }
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程式碼
- 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;
- publicclass BuyServlet extends HttpServlet {
- @Override
- protectedvoid 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;
- publicclass ListServlet extends HttpServlet {
- @Override
- protectedvoid 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;
- publicclass LoginServlet extends HttpServlet {
- @Override
- protectedvoid 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/>");
- }
- }
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程式碼
- <!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">
- 使用者名稱:<inputtype="text"name="username"><br/>
- 密碼:<input type="text"name="password"><br/>
- <input type="submit"value="登入">
- </form>
- </body>
- </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程式碼
- <!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">
- 貨品:<selectname="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>
<!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程式碼
- <?xml version="1.0"encoding="UTF-8"?>
- <web-app xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- version="2.5">
- <servlet>
- <servlet-name>LoginServlet</servlet-name>
- <servlet-class>cn.itcast.cd.servlet.LoginServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>LoginServlet</servlet-name>
- <url-pattern>/login</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>BuyServlet</servlet-name>
- <servlet-class>cn.itcast.cd.servlet.BuyServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>BuyServlet</servlet-name>
- <url-pattern>/buy</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>ListServlet</servlet-name>
- <servlet-class>cn.itcast.cd.servlet.ListServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>ListServlet</servlet-name>
- <url-pattern>/list</url-pattern>
- </servlet-mapping>
- </web-app>