Session small item Session

Product class:

package Session;
public class Product {
private int id;
    private String name;
    private String describe;
    private float price;
public Product(int id,String name, String describe, float price) {
super();
this.id=id;
this.name = name;
this.describe = describe;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}

}

productItem class:

package Session;
/*
 * Store purchased items
 * Store as the basic object of List and store in session
 */
public class productItem {
     Product product;
     private int quantity;
public productItem(Product product, int quantity) {
super();
this.product = product;
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}

}

ShopingServlet class:

package Session;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
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;
/*
 * Mainly divided into three parts
 * The first part: display the product
 * The second Part: Product Navigation
 * Part Three: Shopping Cart Display
 */
@WebServlet(name="ShopingServlet",urlPatterns= {"/products","/pref","/cart"})
public class ShopingServlet extends HttpServlet{
// Store the list of all products in the mall
List<Product> products=new ArrayList<Product>();
//Set the unique attribute name in session
private static final String AtrributeName="Cart";
   /*
    * Initialize product information
    * 
    */
@Override
public void init() throws ServletException {
//Add product
       Product p1=new Product(1, "Keyboard", "Mingsong Digital Store", 123);
       Product p2=new Product(2, "Mouse", "Boiling Times Store", 234);
       Product p3=new Product(3, "Sneakers", "Forest Giant Store", 333);
       Product p4=new Product(4, "Basketball", "Jordan Store", 890);
       //Add to the list
       products .add(p1);
       products.add(p2);
       products.add(p3);
       products.add(p4);
       }
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Requesting");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
/ /Get its request
String select=req.getRequestURI();
//Determine the purpose of the request
if(select.endsWith("/products")) { //Browse products
sentProductList(resp);
}else if(select.endsWith(" /pref")){ //Product navigation
ShowProductDetial(req,resp);
}else if(select.endsWith("/cart")){ //Shopping cart display
cart(req,resp);
}else {
System.out .println("GG!!");//The web address does not exist
}
} /** * Product browsing



* Home page
*/
private void sentProductList(HttpServletResponse resp) throws IOException {
   //Get the print object
PrintWriter pw=resp.getWriter();
//Document output part
pw.println("<html><head></head>< body>");
pw.println("**Online shopping mall:");
pw.println("<ul>");
for (Product product : products) {
pw.println("<li>"+product.getName ()+"<a href='pref?id="+product.getId()+"'>---->enter</a>"+"</li>");//With related product details Link to information
}
pw.println("</ul><a href='cart'> shopping cart</a>");
pw.println("</body></html>");
}
/**
* Show product specific information

*/
private void ShowProductDetial(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//Parse and get the id of the related product in the URL
String productId=req.getParameter("id");
System.out.println(productId);
int id=0;
try {
id=Integer.parseInt(productId);
System. out.println(id);
} catch (Exception e) {
System.out.println("Parsing exception!!!");
}
//The product to be displayed
Product product=null;
//Query related products
for (Product it : products) {
if(id==it.getId()) { //Find the product to be queried
product=it;
break;
}
}
/**
* Purchase product form
*/
//Enter the product details
//Get the print object
PrintWriter pw=resp.getWriter();
pw.println("<html><head></head><body>");
pw.println("<input type='hidden' name='id' value="+product.getId()+">");                       //通过隐藏域进行会话
pw.println("<ul><li>");
pw.println("name:"+product.getName()+"</li>");
pw.println("<li>describe:"+product.getDescribe()+"</li>");
pw.println("<li>price:¥"+product.getPrice()+"</li>");
pw.println("</ul><form method='post'>");
//表单部分
pw.println("quantity:<input name='num' type='text'>");
pw.println("<input type='submit' value='确定'></form><br/>");
pw.println("<a href='products'>back</a>");                    @Override*/* put the selected item in the shopping cart* post-purchase form processing/**}
pw.println("</body></html>");






protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Parse the URL to get the id of the related product
   String productId=req.getParameter("id");
   int id=0;
try {
id=Integer.parseInt (productId);
System.out.println(id);
} catch (Exception e) {
System.out.println("Parsing exception!!!");
}
//The product to be displayed
Product product=null;
//Query Related products
for (Product it : products) {
if(id==it.getId()) { //Find the product to be queried
product=it;
break;
}
}
int num=0;
   num=Integer.parseInt(req. getParameter("num"));
//Object
productItem item=null;
item=new productItem(product, num);
//Get Session object
HttpSession session=req.getSession(); @SuppressWarnings
("unchecked")
List<productItem> cart=(List<productItem>) session.getAttribute(this.AtrributeName);
if(cart==null) { //Add an item for the first time
       cart=new ArrayList<productItem>();
}
//Set the encoding method
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//printWriter
PrintWriter pw =resp.getWriter();
pw.println("<html><head></head><body>");
if(num>0) {
cart.add(item);
session.setAttribute(this.AtrributeName, cart);
  //Return after submitting
  //Get the print object
  pw.println("Purchase successful!!!<br/>");
}else {
  pw.println("   购买失败!!!<br/>    ");
}
pw.println("<a href='products'>back</a>");
pw.println("</body></html>");
}
/**
* 购物车展示
*/
private void cart(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//获取Sesssion对象
HttpSession session=req.getSession();
List<productItem>products=(List<productItem>) session.getAttribute(this.AtrributeName);
//获取打印对象
PrintWriter pw=resp.getWriter();
pw.println("<html><head></head><body><ul>");if(products!=null) {for (productItem it : products) {pw.println("<li>"+it.product.getName()+":"+it.getQuantity()+"</li>");}}else {






pw.println("<li>NO select products!!!</li>");
}
pw.println("</ul>"
+"<a href='products'>               back</a>"
+ "</body></html>");
}


}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324728263&siteId=291194637