Java Web之網上購物系統(注冊、登錄、瀏覽商品、添加購物車)


眼看就要期末了,我的專業課也迎來了第二次的期末作業---------《網上購物系統》。雖然老師的意圖是在鍛煉我們后台的能力,但是想着還是不利用網上的模板,准備自己寫,以來別人寫的靜態頁看不懂,再着可以鍛煉自己做網頁的能力。所以趁有點小進展就想分享自己的作業進展狀態。下面是我頁面運行的截圖。

可能粘貼的圖片沒有任何的效果可言,下面.jsp字體可以運行你想要的頁面效果。

index.jsp

register.jsp

login.jsp

product.jsp

后台代碼:

 

User.java

 

 

package cn.edu.aynu.rjxy.bean;
/**
 * 商城用戶屬性
 * @author Administrator
 *
 */
public class User {
    private String id;
    private String username;
    private String password;
    private String name;
    private String telephone;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    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;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    
}

 

Product.java
package cn.edu.aynu.rjxy.bean;
/**
 * 商品屬性
 * @author Administrator
 *
 */
public class Product {
    private String id;
    private String name;
    private Double price;
    private String category;
    private int pnum;
    private String imgurl;
    private String description;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    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 String getCategory() {
        return category;
    }
    public void setCategory(String category) {
        this.category = category;
    }
    public int getPnum() {
        return pnum;
    }
    public void setPnum(int pnum) {
        this.pnum = pnum;
    }
    public String getImgurl() {
        return imgurl;
    }
    public void setImgurl(String imgurl) {
        this.imgurl = imgurl;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    
}
UserDao.java
package cn.edu.aynu.rjxy.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.edu.aynu.rjxy.bean.User;
import cn.edu.aynu.rjxy.utils.JDBCUtils;

/**
 * 對User表的操作
 * @author Administrator
 *
 */
public class UserDao {
    QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
    /**
     * 添加用戶到user表
     * @throws SQLException 
     */
    public void add(User user) throws SQLException{
        String sql = "insert into user(id,username,password) values(?,?,?)";
        qr.update(sql, user.getId(),user.getUsername(),user.getPassword());
    }
    /**
     * 通過用戶名查找用戶
     * @throws SQLException 
     */
    public User findByUsername(String username) throws SQLException{
        String sql = "select * from user where username = ?";
        User user = qr.query(sql, new BeanHandler<User>(User.class),username);
        return user;
    }
}
ProductDao.java
package cn.edu.aynu.rjxy.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.edu.aynu.rjxy.bean.Product;
import cn.edu.aynu.rjxy.utils.JDBCUtils;

/**
 * 對product表進行增刪改查
 * @author Administrator
 *
 */
public class ProductDao {
    QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
    //查詢所有商品
    public List<Product> findAll() throws SQLException{
        String sql = "select * from product";
        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return list;
    }
    //根據id查找商品
    public Product findProductById(String id) throws SQLException{
        String sql = "select * from product where id=?";
        return qr.query(sql, new BeanHandler<Product>(Product.class),id);
    }
}
UserException
package cn.edu.aynu.rjxy.exception;

public class UserException extends Exception {

    public UserException() {
        super();
    }

    public UserException(String message, Throwable cause) {
        super(message, cause);
    }

    public UserException(String message) {
        super(message);
    }

    public UserException(Throwable cause) {
        super(cause);
    }

}
UserService 
package cn.edu.aynu.rjxy.service;

import java.sql.SQLException;

import cn.edu.aynu.rjxy.bean.User;
import cn.edu.aynu.rjxy.dao.UserDao;
import cn.edu.aynu.rjxy.exception.UserException;

/**
 * 調用dao層的方法
 * @author Administrator
 *
 */
public class UserService {
    private UserDao userDao = new UserDao();
    /**
     * 用戶注冊
     * 1、檢測輸入的用戶名是否存在,如果存在拋出異常“用戶已存在”
     * 2、把輸入的用戶添加到數據庫中的user表
     * @throws UserException 
     */
    public void register(User user) throws UserException{
        try {
            //檢測用戶是否存在
            User u = userDao.findByUsername(user.getUsername());
            //如果存在拋出異常否則添加用戶到user表
            if (u != null) {
                throw new UserException("用戶已經存在");
            }else{
                userDao.add(user);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 用戶登錄
     * @throws UserException 
     */
    public User login(User user) throws UserException{
        try {
            //根據用戶名查詢user表得到user對象u
            User u = userDao.findByUsername(user.getUsername());
            /**
             * 如果u為null,說明用戶不存在,拋出異常,顯示用戶不存在
             * 否則說明用戶存在,檢測u對象中的密碼和用戶輸入的面貌是否一致
             * 如果一致,返回查詢到的u否則拋出異常,顯示密碼錯誤
             */
                if(u == null){
                    throw new UserException("用戶名不存在");
                }
                //查詢到的用戶密碼和用戶名輸入的密碼不一致
                if(!u.getPassword().equals(user.getPassword())){
                    throw new UserException("密碼錯誤");
                }
                return u;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        
    }
}
ProductService 
package cn.edu.aynu.rjxy.service;

import java.sql.SQLException;
import java.util.List;

import cn.edu.aynu.rjxy.bean.Product;
import cn.edu.aynu.rjxy.dao.ProductDao;

/**
 * 調用ProductDao的方法
 * @author Administrator
 *
 */
public class ProductService {
    private ProductDao pDao = new ProductDao();
    //查詢所有商品
    public List<Product> findAll(){
        try {
            return pDao.findAll();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //查看某一商品
    public Product findById(String id){
        try {
            return pDao.findProductById(id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
UserServlet 
package cn.edu.aynu.rjxy.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 cn.edu.aynu.rjxy.bean.User;
import cn.edu.aynu.rjxy.exception.UserException;
import cn.edu.aynu.rjxy.service.UserService;
import cn.edu.aynu.rjxy.utils.CommonsUtils;
/**
 * 調用UserService里面的方法
 * @author Administrator
 *
 */
public class UserServlet extends HttpServlet {

    private UserService userService = new UserService();
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
        
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //處理中文亂碼
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //獲取隱藏字段method的值,並把它轉換為int型
        int method = Integer.parseInt(request.getParameter("method"));
        
        switch (method) {
        case 1:    this.register(request, response);
                break;
        case 2:    this.login(request, response);
                break;
        
        }
    }
    public void register(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        /**
         * 1、將注冊表單中的用戶信息封裝到user對象中
         * 2、將獲取的UUID值作為user對象的id
         * 3、注冊,如果發生異常,就到register.jsp頁面上顯示:用戶已存在
         *           如果成功,顯示注冊成功,3秒后就跳轉到index.jsp頁面。    
         */
        User user = CommonsUtils.toBean(request.getParameterMap(), User.class);
        user.setId(CommonsUtils.uuid());
        try {
            userService.register(user);
            request.setAttribute("msg", "注冊成功");
            request.getRequestDispatcher("/jsp/index.jsp").forward(request, response);
        } catch (UserException e) {
            request.setAttribute("msg", e.getMessage());
            //將用戶在注冊表單中輸入的信息保存在request域中,請求轉發的register.jsp,目的回顯
            request.setAttribute("user", user);
            request.getRequestDispatcher("/jsp/register.jsp").forward(request, response);
        }
    }
    
    
    
    public void login(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        /**
         * 1、將用戶登錄表單中的信息封裝成User對象
         * 2、登錄,如果發生異常,就轉發到login.jsp頁面,顯示:異常信息
         *          如果成功,就將查詢到的user對象u,存放到session域中
         *          然后轉發到shopping.jsp頁面,顯示:歡迎用戶登錄
         */
        User user = CommonsUtils.toBean(request.getParameterMap(), User.class);
        System.out.println(user+"-------->");
         try {
            User u = userService.login(user);
            System.out.println(u+">>>>");
            //將u存放到session域中
            request.getSession().setAttribute("user", u);
            request.getRequestDispatcher("/jsp/index.jsp").forward(request, response);
        } catch (UserException e) {
            request.setAttribute("msg", e.getMessage());
            request.setAttribute("user", user); //回顯
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
        }
    }
}
ProductServlet 
package cn.edu.aynu.rjxy.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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.edu.aynu.rjxy.bean.Product;
import cn.edu.aynu.rjxy.service.ProductService;
/**
 * 調用ProductService的方法
 * @author Administrator
 *
 */
public class ProductServlet extends HttpServlet {
    private ProductService ps = new ProductService();
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //處理中文亂碼
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //獲取隱藏字段method的值,並把它轉換為int型
        int method = Integer.parseInt(request.getParameter("method"));
        
        switch (method) {
        case 1:    this.findAll(request, response);
                break;
        case 2:    this.addCart(request, response);
                break;
      
        
        }
        
    }
    //處理查詢所有商品的請求
    public void findAll(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        List<Product> list = ps.findAll();
        request.setAttribute("listProduct", list);
        //通過請求轉發將商品信息顯示在product.jsp頁面上
        request.getRequestDispatcher("/jsp/product.jsp").forward(request, response);
}
    //處理添加購物車的請求
    public void addCart(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        //獲取商品的id
        String id = request.getParameter("id");
        //得到商品
        Product p = ps.findById(id);
        //購物車是保存在session中
        HttpSession session = request.getSession();
        //從session中拿到購物車
        Map<Product,Integer> cart = (Map<Product, Integer>) session.getAttribute("cart");
        //如果cart不存在,就創建購物車
        if (cart == null) {
            cart = new HashMap<Product,Integer>();
        }
        /**
         * 遍歷Map中的所有key也就是商品對象,如果發現有的商品的id和
         * 即將加入購物車的id相同,就在原來的數量上+1
         */
        Iterator<Product> it = cart.keySet().iterator();
        boolean f = true;
        while (it.hasNext()) {
            Product pp = (Product)it.next();
            if (pp.getId().equals(p.getId())) {
                cart.put(pp, cart.get(pp)+1);
                f = false;
            }
        }
        //如果沒有發現購物車原來相同的商品,就直接加入
        if (f) {
            cart.put(p, 1);
        }
        //將cart放入session
        session.setAttribute("cart", cart);
        //重定向
        response.sendRedirect("jsp/cart.jsp");

}
   
}
CommonsUtils
package cn.edu.aynu.rjxy.utils;

import java.util.Map;
import java.util.UUID;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

/**
 * 提供UUID,實現表單數據封裝到bean中
 * @author Administrator
 *
 */
public class CommonsUtils {
    /**
     * 返回一個UUID
     * @return
     */
    public static String uuid(){
        return UUID.randomUUID().toString().replace("-", "").toUpperCase();
        
    }
    
    /**
     * 把表單數據封裝到bean中
     */
    public static <T> T toBean(Map data, Class<T> clazz){
        try{
            T bean = clazz.newInstance();
            BeanUtils.populate(bean, data);
            return bean;
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    
}

JDBCUtils

package cn.edu.aynu.rjxy.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 創建數據庫連接池
 * @author Administrator
 *
 */
public class JDBCUtils {
    //讀取的是C3P0-config默認配置創建數據庫連接池對象
    private static DataSource ds = new ComboPooledDataSource();
    //獲取數據庫連接池對象
    public static DataSource getDataSource(){
        return ds;
    }
    //從池中獲取連接
    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }    
}

c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 默認配置,當使用ComboPooledDataSource無參構造器時,使用的就是這個配置 -->
    <default-config>
        <!-- 基本配置 -->
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">123456</property>
        <!-- 每次增量,當需要創建Connection對象時,一次創建幾個 -->
        <property name="acquireIncrement">3</property>
        <!-- 當創建池對象后,池中應該有幾個Connection對象 -->
        <property name="initialPoolSize">10</property>
        <!-- 池中最少Connection個數,如果少於這個值,就會創建Connection -->
        <property name="minPoolSize">2</property>
        <!-- 池中最大連接個數 -->
        <property name="maxPoolSize">10</property>
    </default-config>
</c3p0-config>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM