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>
原文地址:https://www.cnblogs.com/kangyaping/p/6158270.html