Javaweb Experiment Five

Source: Internet
Author: User

Product class:

Package Com.lab;
public class Product {
private int id; Product number
private String name; Product Name
Private String description; Product Description
private float price; Commodity price
Construction method
public Product (int ID, string name, string description, float price) {
This.id = ID;
THIS.name = name;
this.description = description;
This.price = Price;
}
Setter methods and Getter methods for each attribute
public int getId () {
return ID;
}
public void setId (int id) {
This.id = ID;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public String getdescription () {
return description;
}
public void SetDescription (String description) {
this.description = description;
}
public float GetPrice () {
return price;
}
public void Setprice (float price) {
This.price = Price;
}
}

Showshoppingitem class:

Shoppingcartservlet

Package Com.lab;
Import com.lab.Product;
Import Com.lab.ShoppingItem;
Import java.io.*;
Import java.util.ArrayList;
Import java.awt.List;
Import java.util.List;
Import java.awt.Component;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.Serializable;
Import Javax.servlet.annotation.WebServlet;

@WebServlet (name = "Shoppingcartservlet", Urlpatterns = {
"/products", "/viewproductdetails",
"/addtocart", "/viewcart", "/deleteitem"})

public class Shoppingcartservlet extends HttpServlet {


Products are list objects that store all items
Private List <Product> products = new ArrayList <Product> ();

@Override
public void Init () throws Servletexception {
Products.add (New Product (1, "SLR Camera",
"Nikon's most cost-effective SLR camera", 4159.95F));
Products.add (New Product (2, "Samsung Phone",
"Samsung's newest IPhone5 product", 1199.95F));
Products.add (New Product (3, "laptop",
"Lenovo's next-generation products", 5129.95F));
Products.add (New Product (4, "Tablet PC",
"Apple's new Product", 1239.95F));
}

@Override
public void doget (HttpServletRequest request,
HttpServletResponse response) throws Servletexception,
IOException {
String uri = Request.getrequesturi ();
Determines which method to invoke based on the request URI
if (Uri.endswith ("/products")) {
Showproductlist (response);
} else if (Uri.endswith ("/viewproductdetails")) {
Showproductdetails (request, response);
} else if (Uri.endswith ("Viewcart")) {
Showcart (request, response);
} else if (Uri.endswith ("DeleteItem")) {
DeleteItem (request, response);
}
}


This method is used to display all product information
private void Showproductlist (HttpServletResponse response)
Throws IOException {
Response.setcontenttype ("text/html;charset=gb2312");
PrintWriter out = Response.getwriter ();
Out.println (""Out.println ("<ul>");
for (Product product:products) {
Out.println ("<li>" + product.getname () + "("
+ Product.getprice ()
+ ") (" + "<a href= ' viewproductdetails?id="
+ Product.getid () + "' > Details </a>)");
}
Out.println ("</ul>");
Out.println ("<a href= ' Viewcart ' > View shopping cart </a>");
Out.println ("</body>}


private void Showproductdetails (HttpServletRequest request,
HttpServletResponse response) throws IOException {
Response.setcontenttype ("text/html;charset=gb2312");
PrintWriter out = Response.getwriter ();
int productId = 0;
try {
ProductId = Integer.parseint (
Request.getparameter ("id"));
} catch (NumberFormatException e) {
}
Return commodity objects by product number
Product Product = GetProduct (productId);

if (product! = NULL) {
Out.println ("+ "<title> Product Details </title>+ "<body><p> Product Details </p>"
+ "<form method= ' post ' action= ' AddToCart ' >");
Use hidden form fields to store product number information here
Out.println ("<input type= ' hidden ' name= ' id '"
+ "value=" + productId + "'/>");
Out.println ("<table>");
Out.println ("<tr><td> Product name:</td><td>"
+ product.getname () + "</td></tr>");

OUT.PRINTLN ("<tr><td> description:</td><td>"
+ product.getdescription () + "</td></tr>");
Out.println ("<tr><td> Price:</td><td>"
+ product.getprice () + "</td></tr>");

Out.println ("<tr>" + "<tr>"
+ "<td><input name= ' quantity '/></td>"
+ "<td><input type= ' submit ' value= ' buy '/> '
+ "</td>"
+ "</tr>");
Out.println ("<tr><td colspan= ' 2 ' >"
+ "<a href= ' products ' > product List </a>"
+ "</td></tr>");
Out.println ("</table>");
Out.println ("</form></body>");
} else {
Out.println ("No product found");
}
}


Return commodity object method according to product number
Private Product getproduct (int productId) {
for (Product product:products) {
if (product.getid () = = ProductId) {
return product;
}
}
return null;
}


public void DoPost (HttpServletRequest request,
                        httpservletresponse Response)
Throws Servletexception, IOException {
    //Add purchased items to cart
     int productId = 0;
     int quantity = 0;
     try {
         productId = Integer.parseint (
                     request.getparameter ("id"));
         quantity = integer.parseint (Request
                    . GetParameter ( "Quantity"));
    } catch (NumberFormatException e) {}

Product Product = GetProduct (productId);
if (Product = null && quantity >= 0) {
Create a product entry
Shoppingitem Shoppingitem = new Shoppingitem (
product, quantity);
HttpSession session = Request.getsession ();
Find the shopping Cart object in the Session object
list<shoppingitem> cart = (list<shoppingitem>) session
. getattribute ("cart");
if (cart = = null) {
If the shopping cart object is not found on the session object, create a
Cart = new arraylist<shoppingitem> ();
Store the shopping Cart object on the Session object
Session.setattribute ("cart", cart);
}
Add a product to the shopping cart object
Cart.add (Shoppingitem);
}
Showproductlist (response);
}



private void Showcart (HttpServletRequest request,
HttpServletResponse response) throws IOException {
Response.setcontenttype ("text/html;charset=gb2312");
PrintWriter out = Response.getwriter ();
Out.println ("Out.println ("<body><a href= ' products ' >" +
"Product List </a>");
HttpSession session = Request.getsession ();
list<shoppingitem> cart = (list<shoppingitem>) session
. getattribute ("cart");
if (cart! = null) {
Out.println ("<table>");
Out.println ("<tr><td style= ' width:50px ' > Quantity"
+ "</td>"
+ "<td style= ' width:80px ' > Products </td>"
+ "<td style= ' width:80px ' > Price </td>"
+ "<td style= ' width:80px ' > Subtotal </td>"
+ "<td style= ' width:80px ' > Delete </td></tr>");

Double total = 0.0;
for (Shoppingitem Shoppingitem:cart) {
Product Product = Shoppingitem.getproduct ();
int quantity = Shoppingitem.getquantity ();
if (Quantity! = 0) {
float price = Product.getprice ();
Out.println ("<tr>");
Out.println ("<td>" + quantity + "</td>");
Out.println ("<td>" + product.getname ()
+ "</td>");
Out.println ("<td>" + price + "</td>");
Calculate subtotals and implement rounding
Double subtotal = ((int) (price * quantity*100+0.5))/100.00;
Out.println ("<td>" + Subtotal + "</td>");
Out.println ("<td><a href=deleteitem?id=" +
Product.getid () + ">" + "delete </a>" + "</td>");
Total + = subtotal;
Out.println ("</tr>");
}
}
Out.println ("<tr><td colspan= ' 4 '"
+ "style= ' text-align:right ' >"
+ "Total:" + totals + "</td></tr>");
Out.println ("</table>");
}
Out.println ("</table></body>}
}

Javaweb Experiment Five

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.