Shopping Cart [HttpSession] – Ứng dụng Giỏ hàng Cơ bản [Servlet]


Bài trước mình có giới thiệu cho các bạn qua đối tượng HttpSeesion . Hôm nay mình làm thêm 1 demo về 1 giỏ hàng đơn giản thông qua đối tượng httpsession. Hy vọng bài viết giúp ích các bạn .

Cấu trúc thư mục😦 Ở đây mình dùng Servlet 3.0 ) nên các bạn để ý . Mình sẻ dùng luôn thằng @webservlets (/duongdan). Nếu các bạn sử dụng phiên bản về trước thì phải mapping thằng servlet trong file web.xml (nếu ai thắc mắc thì có thề liên hệ mình rồi mình hướng dẫn).

Hình ảnh của ứng ụng :

Tạo đối tượng Book.java

</pre>
package shopping;
/**
 *
 * @author kobe
 *
 */
public class Book {
 private String name;
 private double price;
 private int amount;

 public Book() {
 super();
 // TODO Auto-generated constructor stub
 }
 public Book(String name, double price, int soluong) {
 super();
 this.name = name;
 this.price = price;
 this.amount = soluong;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public double getPrice() {
 return price;
 }
 public void setPrice(double price) {
 this.price = price;
 }
 public int getAmount() {
 return amount;
 }
 public void setAmount(int amount) {
 this.amount = amount;
 }
 @Override
 public int hashCode() {
 final int prime = 31;
 int result = 1;
 result = prime * result + ((name == null) ? 0 : name.hashCode());
 return result;
 }
 @Override
 public boolean equals(Object obj) {
 if (this == obj)
 return true;
 if (obj == null)
 return false;
 if (getClass() != obj.getClass())
 return false;
 Book other = (Book) obj;
 if (name == null) {
 if (other.name != null)
 return false;
 } else if (!name.equals(other.name))
 return false;
 return true;
 }
 @Override
 public String toString() {
 return name + "-" + price + "-" + amount;
 }
}
<pre>

Cart.java

</pre>
package shopping;

import java.util.ArrayList;
/**
 *
 * @author kobe
 *
 */
public class Cart {
 private ArrayList<Book> cart;

public Cart() {
 cart = new ArrayList<Book>();
 }

 public void AddBook(Book book){
 if(cart.contains(book)){
 Book b = cart.get(cart.indexOf(book));
 b.setAmount(b.getAmount()+book.getAmount());
 }else{
 cart.add(book);
 }
 }

 public Book GetBook(int i){
 if(i<0 || i> cart.size()-1)
 return null;
 else
 return cart.get(i);
 }

 public boolean DelBook(String name){
 Book book = new Book(name, 0d, 0);
 if(cart.contains(book)){
 cart.remove(book);
 return true;
 }
 return false;
 }

 public int NumberOfBook(){
 return cart.size();
 }

 public double Total_Money(){
 double money = 0d;
 for(Book bk : cart)
 money += (bk.getPrice()*bk.getAmount());
 return money;
 }
}
<pre>

Servlet Shop.java

</pre>
package shopping;

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

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

/**
 * @author kobe
 * Servlet implementation class Shop
 */
@WebServlet("/shop")
public class Shop extends HttpServlet {
 private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 doPost(request, response);
 }

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
 HttpSession session = request.getSession();
 double total = 0d;
 synchronized (session) {
 out.println("<html>");
 out.println("<head><title>Shop Book</title></head>");
 out.println("<body bgcolor=\"#fdf5e6\">");
 out.println("<h1>Welcome to Shop Book</h1>");
 out.println("<form action=\"process\" method=\"post\">"+
 "<p>Select Book : "+ "<select name=\"cboBook\">"+
 "<option>Ajax</option>"+
 "<option>PHP</option>"+
 "<option>Java</option>"+
 "<option>C#</option>"+
 "<option>JSP</option>"+"</select>"+
 "Amount : <input type=\"text\" name=\"tfAmout\" value=\"1\">"+
 " <input type=\"submit\" value=\"Buy\"> "+
 "<p><h2>Infomation of Your Cart</h2>"+
 "<table border=\"1\" width=\"80%\">"+
 "<tr>"+
 "<td>Order</td>"+
 "<td>Product</td>"+
 "<td>Amout</td>"+
 "<td>Price</td>"+
 "<td>Total</td>"+
 "</tr>");
 Cart cart = (Cart) session.getAttribute("cart");
 if(cart==null)
 cart = new Cart();
 total = cart.Total_Money();
 int order;
 for(int i = 0;i<cart.NumberOfBook();i++){
 Book bk = cart.GetBook(i);
 order = i;
 out.println("<tr>"+
 "<td>"+ ++order +"</td>"+
 "<td>"+bk.getName()+"</td>"+
 "<td>"+bk.getAmount()+"</td>"+
 "<td>"+bk.getPrice()+"</td>"+
 "<td>"+bk.getAmount()*bk.getPrice()+"</td>"+
 "</tr>");
 }
 out.println("</table>"+
 "<h2>Total : " + total +"$</h2>");
 out.println("</form>");
 out.println("</body>");
 out.println("</html>");
 }
 }

}
<pre>

Servlet Process

</pre>
package shopping;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Process
 */
@WebServlet("/process")
public class Process extends HttpServlet {
 private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 doPost(request, response);
 }

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 HttpSession seesion = request.getSession();
 synchronized (seesion) {
 Cart cart = (Cart) seesion.getAttribute("cart");
 if(cart == null)
 cart = new Cart();
 String book = request.getParameter("cboBook");
 String amout = request.getParameter("tfAmout");
 int am = Integer.parseInt(amout);
 if(am>0){
 double price = checkPrice(book);
 Book bk = new Book(book, price, am);
 cart.AddBook(bk);
 seesion.setAttribute("cart", cart);
 }
 }
 RequestDispatcher dispatcher = request.getRequestDispatcher("/shop");
 dispatcher.forward(request, response);
 }

 private double checkPrice(String str){
 switch (str) {
 case "Ajax":return 10000d;
 case "PHP":return 15000d;
 case "Java":return 20000d;
 case "C#":return 14000d;
 case "JSP":return 25000d;
 }
 return 0;
 }

}
<pre>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: