本文将带领大家实现第一个用eclipse写的第一个Javaweb项目–简单购物车。文章会在问题分析、具体实现和常见问题这三块为大家详细解说。
问题分析:
首先我们要了解我们要完成的是什么----购物车。然后那实现购物车的什么呢?是不是往购物车添加心仪商品呢。那是不是还要实现价格的计算呢?既然我们了解问题本质了,那我们接下来就要进行具体实现了。
具体实现:
首先我们要看一下项目整体的结构
下面我们要先创建实体类,就是我们的商品、预购商品和购物车这三个实体类。
Beans
Cart类(这个类是购物车实体类,包含了购物车中添加的商品和总计两个属性。)
package Beans;
import java.util.HashMap;
public class Cart {
private HashMap<String,CartItem> cartItems=new HashMap<String,CartItem>();//购物车中添加的商品
private double total;//总计
public HashMap<String, CartItem> getCartItems() {
return cartItems;
}
public void setCartItems(HashMap<String, CartItem> cartItems) {
this.cartItems = cartItems;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
}
CartItem类(这个是购物车中添加的商品类,包含有商品、商品个数和小计)
package Beans;
public class CartItem {
private Product product;//商品
private int buyNum;//个数
private double subTotal;//小计
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getBuyNum() {
return buyNum;
}
public void setBuyNum(int buyNum) {
this.buyNum = buyNum;
}
public double getSubTotal() {
return subTotal;
}
public void setSubTotal(double subTotal) {
this.subTotal = subTotal;
}
}
Product类 (这里是具体的商品类,包含有商品编号、商品名和商品价格三个属性)
package Beans;
public class Product {
private String pid;//商品编号
private String name;//商品名
private double price;//商品价格
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
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 Product(String pid,String name,double price) {
// TODO Auto-generated constructor stub
this.pid = pid;
this.name = name;
this.price = price;
}
}
Service
这个包下面只有一个类,主要的作用是存入商品,并能根据商品编号找到商品。
ProductService类
package Service;
import java.util.HashMap;
import Beans.CartItem;
import Beans.Product;
public class ProductService {
private HashMap<String,CartItem> cartItems=new HashMap<String,CartItem>();
public ProductService() //构造函数
{
CartItem cartltem1=new CartItem();
CartItem cartltem2=new CartItem();
Product product1=new Product("001","Mobilephone",1000);
Product product2=new Product("002","Watch",100);
cartltem1.setProduct(product1);
cartltem2.setProduct(product2);
cartItems.put("001",cartltem1);
cartItems.put("002", cartltem2);
}
public Product findProductbypid(String pid)
{
CartItem cartItem=cartItems.get(pid);
Product product=cartItem.getProduct();
return product;
}
}
Servelet
ProductServlet类 (在这经常会报错 1、httpservelet类无法继承;因为httpservelet类是在tomcat下的所以这里可能是tomcat没有配置入项目或者httpservelet类没有导入,所以要重新导入tomcat。2、dopost和doget两种基础方法使用错误,导致页面传来的数据无法进行处理;解决:servelet类中的方法要与页面选择方法一致。3、乱码,中文乱码;解决:中文的编码最好用utf-8【servlet改编码是对req、resp设置】,并且页面和后台采用的编码要一致。)
这里的路径配置采用的是标签(方便)、也可采用.xml配置.
package Servlet;
import java.io.IOException;
import java.util.HashMap;
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;
import Beans.Cart;
import Beans.CartItem;
import Beans.Product;
import Service.ProductService;
@WebServlet("/productServlet")
public class ProductServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ProductService productService = new ProductService();
String pid=(String)req.getParameter("Product");
int buyNum=Integer.parseInt(req.getParameter("number"));
HttpSession session=req.getSession();
Cart cart=(Cart)session.getAttribute("cart");
if(cart==null) {
cart=new Cart();
}
CartItem cartItem=new CartItem();
cartItem.setBuyNum(buyNum);
Product product=productService.findProductbypid(pid);
cartItem.setProduct(product);
double subTotal=product.getPrice()*buyNum;
cartItem.setSubTotal(subTotal);
HashMap<String, CartItem> cartItems=cart.getCartItems();
double newSubTotal=0;
if(cartItems.containsKey(pid)) {
CartItem item=cartItems.get(pid);
int oldBuyNum= item.getBuyNum();
oldBuyNum=oldBuyNum+buyNum;
item.setBuyNum(oldBuyNum);
double oldSubTotal= item.getSubTotal();
newSubTotal=buyNum*product.getPrice();
oldSubTotal=oldSubTotal+newSubTotal;
item.setSubTotal(oldSubTotal);
}
else {
cartItems.put(pid, cartItem);
newSubTotal=buyNum*product.getPrice();
}
double total=cart.getTotal()+newSubTotal;
cart.setTotal(total);
cart.setCartItems(cartItems);
session.setAttribute("cart", cart);
req.getRequestDispatcher("cart.jsp").forward(req, resp);
}
}
jsp
cart.jsp
这里一定要导入其他类 ,用<%@ page import=""%>标签。
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@
page import="Beans.Cart"
%>
<%@
page import="Beans.CartItem"
%>
<%@
page import="Beans.Product"
%>
<%@page import="java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% Cart cart=(Cart)request.getSession().getAttribute("cart");
if(cart==null) {
%>
<p>It is nothing!</p>
<%
}
else{
HashMap<String, CartItem> cartItems=cart.getCartItems();
double total=cart.getTotal();
%>
Your product list:<br>
<%
Set<String> keys=cartItems.keySet();
Iterator<String> iter = keys.iterator();
while(iter.hasNext()){
String key= iter.next();
CartItem cartItem=cartItems.get(key);
Product product=cartItem.getProduct();
out.print(product.getName()+" ") ;
out.println("price:"+product.getPrice()+"$") ;
out.println("number:"+cartItem.getBuyNum());
};
%>
<br>
<%
out.print(" total:"+total+"$");
}
%>
</body>
</html>
index.jsp
在action=“”属性的配置是不能只写后台配置的“/productServlet”路径,一定要加上<%=request.getContextPath() %>,否则有可能找不着路径。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Please select the item you want to buy.<br>
<form action="<%=request.getContextPath() %>/productServlet" method="post">
Mobile phone(1000$)
<input name="Product" type="radio" value="001" checked="checked"><br>
Watch(100$)
<input name="Product" type="radio" value="002"><br>
please input the number!
number:<input name="number" type="number"><br>
<input type="submit" value="ok!">
</form>
</body>
</html>