Java Web购物车

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Co_zy/article/details/81139990

登录注册功能

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<title>login</title>
<link href="css/semantic.css"
    rel="stylesheet">
</head>
<body>
    <!-- <p1>test!</p1> -->
    <br>
    <br>
    <br>
    <div class="loginpage">
        <br> <br> <br>
        <h2 align="center">欢迎登录</h2>
        <!--do_login.jsp  -->
        <form name=loginForm action="<%= request.getContextPath() %>/PostServlet" method=post>
            <table align="center">
                <tr>
                    <td>用户名:</td>
                    <td><div class="ui input focus">
                            <input type="text" placeholder="" name=username>
                        </div></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><div class="ui input focus">
                            <input type="password" placeholder="" name=pwd>
                        </div></td>
                <tr />
                <br>


            </table>
            <div class="submit-p">
                <div class="submit-button">
                    <input type="submit" value="login" class="ui primary button" />
                </div>
                <div class="reset-button">
                    <input type="reset" value="reset" class="ui button" />
                </div>
            </div>
        </form>

    </div>

    <style>
.loginpage {
    /*height: 300px;*/
    /*padding-bottom: 64px;*/
    /*height: 500px;*/
    /*position: relative;*/
    height: 400px;
    border: 1px solid #d7d7d7;
    box-shadow: 0 0 20px #d7d7d7;
    background-color: #fff;
    position: absolute;
    width: 382px;
    color: #818181;
    margin: 80px auto;
    position: absolute;
    left: 0;
    right: 0;
}

.submit-button {
    display: inline;
}

.reset-button {
    display: inline;
}

.submit-p {
    margin-left: 120px;
    margin-top:20px;
}
</style>
</body>
</html>

doLogin.jsp

<%@ page language="java" import="dao.*,entity.*,java.util.*,java.sql.*"
    contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%
    String users = request.getParameter("username");
    String pass = request.getParameter("pwd");
    boolean flag = false;
    PreparedStatement sql = null;
    ResultSet rs = null;
    Connection conn = null;
%>

<%
    String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://127.0.0.1:3306/shop";
    String use = "root";
    String password = "password";
    Class.forName(driver);
    conn = DriverManager.getConnection(url, use, password);
    sql = conn.prepareStatement("select * from user where username=? and password=?");
    sql.setString(1, users);
    sql.setString(2, pass);
    rs = sql.executeQuery();
    if (rs.next()) {
        flag = true;
    }
    rs.close();
    sql.close();
    conn.close();
%>
<!-- 判断是否是正确的登录用户 -->
<%
    if (flag == true) {
%>
<jsp:forward page="list.jsp" />
<%
    } else if (flag == false) {
%>
<script>
    alert("用户名或密码错误,请重新输入");
    window.location = "login.jsp";
</script>

<%
    }
%>

注册界面与上面登录界面类似

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<title>注册</title>
https://cdn.bootcss.com/semantic-ui/2.3.1/semantic.css"
    rel="stylesheet">
</head>
<body>
    <!-- <p1>test!</p1> -->
    <br>
    <br>
    <br>
    <div class="loginpage">
        <br> <br> <br>
        <h2 align="center">请注册</h2>
        <form name=loginForm action="doRegister.jsp" method=post>
            <table align="center">
                <tr>
                    <td>用户名:</td>
                    <td><div class="ui input focus">
                            <input type="text" placeholder="" name=username>
                        </div></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><div class="ui input focus">
                            <input type="password" placeholder="" name=pwd>
                        </div></td>
                <tr />
                <br>


            </table>
            <div class="submit-p">
                <div class="submit-button">
                    <input type="submit" value="register" class="ui primary button" />
                </div>
                <div class="reset-button">
                    <input type="reset" value="reset" class="ui button" />
                </div>
            </div>
        </form>

    </div>

    <style>
.loginpage {
    /*height: 300px;*/
    /*padding-bottom: 64px;*/
    /*height: 500px;*/
    /*position: relative;*/
    height: 400px;
    border: 1px solid #d7d7d7;
    box-shadow: 0 0 20px #d7d7d7;
    background-color: #fff;
    position: absolute;
    width: 382px;
    color: #818181;
    margin: 80px auto;
    position: absolute;
    left: 0;
    right: 0;
}

.submit-button {
    display: inline;
}

.reset-button {
    display: inline;
}

.submit-p {
    margin-left: 120px;
    margin-top:20px;
}
</style>
</body>
</html>

doRegister.jsp

<%@ page language="java" import="dao.*,entity.*,java.util.*,java.sql.*"
    contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        request.setCharacterEncoding("utf-8");
        String users = request.getParameter("username");
        String pass = request.getParameter("pwd");
    %>
    <%
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1:3306/shop";
        String use = "root";
        String password = "password";
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, use, password);
        PreparedStatement sql = conn.prepareStatement("insert into user(username,password)values(?,?)");
        sql.setString(1, users);
        sql.setString(2, pass);
        int rtn = sql.executeUpdate();
        sql.close();
        conn.close();
    %>
    <script>
        alert("注册成功");
        window.location = "login.jsp";
    </script>
</body>
</html>

dao下BaseDao.java
用于连接数据库

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.security.auth.x500.X500Principal;

//import com.mysql.jdbc.Statement;

public class BaseDao {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    Connection con;

    public static Connection getConnection() throws SQLException {
        Connection connection = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/shop";
            connection = DriverManager.getConnection(url,"root","password");
        } catch (ClassNotFoundException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return connection;
    }

    public static void closeAll(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}

实体类Product.java

package entity;

import sun.nio.cs.ext.DoubleByteEncoder;

public class Product {
    private int id;
    private String name;
    private double price;
    private String desc;
    private String img;
    private int num;


    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }


    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 double getPrice() {
        return price;
    }


    public void setPrice(double price) {
        this.price = price;
    }


    public String getDesc() {
        return desc;
    }


    public void setDesc(String desc) {
        this.desc = desc;
    }


    public String getImg() {
        return img;
    }


    public void setImg(String img) {
        this.img = img;
    }


    public int getNum() {
        return num;
    }


    public void setNum(int num) {
        this.num = num;
    }

}

ProductDaoImp.java
实现了商品查询的两个方法,一种是findAll()用于商品列表页面
一种是findById()用于商品详情页面

package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import org.apache.tomcat.jni.Proc;
//import java.sql.*;
import org.omg.CORBA.PUBLIC_MEMBER;

import com.sun.org.apache.regexp.internal.recompile;

import entity.Product;
import jdk.internal.org.objectweb.asm.commons.StaticInitMerger;

//操作产品的实现类
public class ProductDaoImp {
    /* 作用,按照条件查询产品 */
    public ArrayList findAll() {

        ArrayList list = new ArrayList();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 1.打开数据库连接
            conn = BaseDao.getConnection();

            // 2.创建执行sql语句对象
            stmt = conn.createStatement();

            // 3.发送sql语句到mysql
            String sql = "select * from product";
            rs = stmt.executeQuery(sql);
            // rs结果集--->遍历--->封装product--->放入ArrayList

            while (rs.next())// 循环一次只代表一行
            {
                Product p = new Product();
                p.setId(rs.getInt("id"));
                p.setName(rs.getString("name"));
                p.setImg(rs.getString("img"));
                p.setDesc(rs.getString("desc"));
                p.setNum(rs.getInt("num"));
                p.setPrice(rs.getDouble("price"));
                System.out.println(p.getName());
                list.add(p);
            }
            // 4.
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(conn, (com.mysql.jdbc.Statement) stmt, rs);
        }
        return list;
    }

    public Product findById(int id) {

        //ArrayList list = new ArrayList();
        Product p = new Product();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 1.打开数据库连接
            conn = BaseDao.getConnection();

            // 2.创建执行sql语句对象
            stmt = conn.createStatement();

            // 3.发送sql语句到mysql
            String sql = "select * from product where id =" + id;
            rs = stmt.executeQuery(sql);
            // rs结果集--->遍历--->封装product--->放入ArrayList

            while (rs.next())// 循环一次只代表一行
            {
                //Product p = new Product();
                p.setId(rs.getInt("id"));
                p.setName(rs.getString("name"));
                p.setImg(rs.getString("img"));
                p.setDesc(rs.getString("desc"));
                p.setNum(rs.getInt("num"));
                p.setPrice(rs.getDouble("price"));
                //System.out.println(p.getName());
                //list.add(p);
            }
            // 4.
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(conn, (com.mysql.jdbc.Statement) stmt, rs);
        }
        return p;
    }
//  public static void main(String[] args)throws Throwable{
//      new ProductDaoImp().findAll();
//  }

}

商品列表界面核心代码

<% 
ProductDaoImp dao = new ProductDaoImp();
ArrayList list = dao.findAll();
for(int i=0;i<list.size();i++){ 
    Product p = (Product)list.get(i);
%>

    <li>
    <a href="detail.jsp?id=<%= p.getId() %>">
        <div class="i-pic limit">
            <img src="images/small-<%= p.getImg() %>" />                                            
            <p class="title fl"><%= p.getName() %></p>
            <p class="price fl">
                <b>¥</b>
                <strong><%= p.getPrice() %></strong>
            </p>
            <p class="number fl">
                销量<span><%= p.getNum() %></span>
            </p>
        </div>
        </a>
    </li>

<%
}
%>

detail界面核心代码

<% 
String idStr = request.getParameter("id");
if("".equals(idStr) || idStr == null){
    response.sendRedirect("login.jsp");
}else{


int id = Integer.parseInt(request.getParameter("id"));
ProductDaoImp dao = new ProductDaoImp();
Product p = dao.findById(id);
%>

......
......省略(用渲染p的各个属性)
......

<%
}
%>

购物车页面

detail.jsp和cart.jsp页面之间通过doCart.jsp来连接

doCart.jsp

<%@ page language="java" import="dao.*,entity.*,java.util.*"
    contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    //1.获得购物车Map
    //getAttribute的返回值类型是Object,需要向下转型,
    //转成你的userName类型的,简单说就是存什么,取出来还是什么.
    HashMap map = (HashMap) session.getAttribute("cart");

    //2.判断购物车Map是否存在,不存在则创建
    if (map == null) {
        map = new HashMap();

    }

    //3.把产品添加到购物车
    //3.1获得添加购物的产品
    //int id = Integer.parseInt(request.getParameter("id"));
    String id = request.getParameter("id");
    ProductDaoImp dao = new ProductDaoImp();
    Product p = dao.findById(Integer.parseInt(id));
    //3.2判断Map中是否由此商品 , 注意这里id不加引号
    CartItem cartItem = (CartItem) map.get(id);
    if (cartItem != null) {
        cartItem.setSum(cartItem.getSum() + 1);
    } else {
        //有--> 把数量+1
        //无--> 把商品放入购物车 数量为1
        cartItem = new CartItem();
        cartItem.setP(p);
        cartItem.setSum(1);
    }
    ///3.3产品加入集合,id+""拼接成字符串型
    map.put(id, cartItem);
    //out.print(map.size());
    //4.把集合存储到session作用域
    session.setAttribute("cart", map);
    response.sendRedirect("cart.jsp");
%>
<%
HashMap map = (HashMap)session.getAttribute("cart");
Iterator it = map.keySet().iterator();
while(it.hasNext()){
    Object key = it.next();
    CartItem cartItem = (CartItem)map.get(key);
    Product p = cartItem.getP();
    int sum = cartItem.getSum();

%>
......
<%
}
%>

用于增删商品数量的js代码

<script>
function fun1(id, price) {
    var sum = parseInt(document.getElementById("sum" + id).value) + 1;
    var m = sum * parseFloat(price);
    document.getElementById("m" + id).innerHTML = m;
    document.getElementById("J_Total").innerHTML = m;
    var sum1 = parseInt(document.getElementsByClassName("text_box")[0].value) + 1;
    document.getElementById("J_SelectedItemsCount").innerHTML = sum1;

}

function fun2(id, price) {
    var sum = parseInt(document.getElementById("sum" + id).value) - 1;
    var m = sum * parseFloat(price);
    document.getElementById("m" + id).innerHTML = m;
    document.getElementById("J_Total").innerHTML = m;

    document.getElementById("J_SelectedItemsCount").innerHTML = document.getElementsByClassName("text_box")[0].value;

}
</script>

猜你喜欢

转载自blog.csdn.net/Co_zy/article/details/81139990