为了账号安全,请及时绑定邮箱和手机立即绑定

图书管理系统【用户、购买、订单模块、添加权限】(1)

标签:
Java
用户模块

要登陆后才能购买,因此我们先写购买模块.

设计实体

    private String id;
    private String username;
    private String password;
    private String email;
    private String cellphone;
    private String address;

    //各种setter、getter
设计数据库表

CREATE TABLE user (

  id        VARCHAR(40) PRIMARY KEY,
  username  VARCHAR(20) NOT NULL,
  cellphone VARCHAR(20) NOT NULL,
  address   VARCHAR(40) NOT NULL,
  email     VARCHAR(30),
  password  VARCHAR(30) NOT NULL

);
编写DAO

/**
 * 用户的登录注册模块
 * 1:登陆
 * 2:注册
 * 3:根据id查找具体的用户
 */
public class UserDaoImpl {

    public void register(User user) {

        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

        String sql = "INSERT INTO user (id,username,cellphone,address,email,password) VALUES(?,?,?,?,?,?)";
        try {

            queryRunner.update(sql, new Object[]{user.getId(),user.getUsername(), user.getCellphone(), user.getAddress(), user.getEmail(), user.getPassword()});
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public User login(String username, String password) {

        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

        String sql = "SELECT * FROM user WHERE username = ? AND password=?";
        try {

            return (User) queryRunner.query(sql, new Object[]{username, password}, new BeanHandler(User.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public User find(String id) {

        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

        String sql = "SELECT * FROM user WHERE id=?";
        try {

            return (User) queryRunner.query(sql, id, new BeanHandler(User.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
测试DAO

public class UserDemo {
    UserDaoImpl userDao = new UserDaoImpl();

    @Test
    public void add() {

        User user = new User();
        user.setId("1");
        user.setUsername("zhong");
        user.setPassword("123");
        user.setCellphone("10085");
        user.setAddress("广州萝岗");
        user.setEmail("40368324234234@QQ.com");

        userDao.register(user);
    }

    @Test
    public void find() {

        String id = "1";
        User user = userDao.find(id);

        System.out.println(user.getEmail());
    }

    @Test
    public void login() {
        String username = "zhong";
        String password = "123";
        User user = userDao.login(username, password);

        System.out.println(user.getAddress());
    }
}
抽取DAO

public interface UserDao {
    void register(User user);

    User login(String username, String password);

    User find(String id);
}
编写Service

    private UserDao userDao = DaoFactory.getInstance().createDao("zhongfucheng.dao.impl.UserDaoImpl", UserDao.class);

    public void registerUser(User user) {
        userDao.register(user);
    }

    public User loginUser(String username,String password) {
        return userDao.login(username, password);
    }

    public User findUser(String id) {
        return userDao.find(id);
    }
前台样式
  • head.jsp

<div id="User">
    用户名:<input type="text" name="username">
    密码:<input type="password" name="password">
    <button name="login">登陆</button>
    <button name="register">注册</button>
</div>
  • head.css

#body {
    position: relative;
}
#user {
    position: absolute;
    margin-top: 130px;
    margin-left: 1364px;
}
  • 效果:

这里写图片描述


实现登陆注册功能

当点击登陆按钮的时候,把数据带过去给Servlet,让Servlet调用BusinessService方法,实现登陆。注册同理.....因此,我们需要用到JavaScript代码

  • head.jsp

<c:if test="${user==null}" >
<div id="User">
    用户名:<input type="text" id="username">
    密码:<input type="password" id="password">
    <button name="login" onclick="login()">登陆</button>
    <button name="register" onclick="register()">注册</button>
</div>
</c:if>

<c:if test="${user!=null}" >
    <div id="User">
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;欢迎您:${user.username}&nbsp;&nbsp;&nbsp;&nbsp;<a href="${pageContext.request.contextPath}/UserServlet?method=Logout">注销</a>
    </div>
</c:if>
  • javaScript代码

    <script type="text/javascript">

        function login() {
            //得到输入框的数据
            var username = document.getElementById("username").value;
            var password = document.getElementById("password").value;

            //跳转到相对应的Servlet上
            window.location.href = "${pageContext.request.contextPath}/UserServlet?method=login&username=" + username + "&password=" + password;
        }

        function register() {

            //跳转到注册页面
            window.location.href = "${pageContext.request.contextPath}/client/register.jsp";
        }
    </script>
  • UserServlet

        String method = request.getParameter("method");

        BussinessServiceImpl service = new BussinessServiceImpl();
        if (method.equals("login")) {

            try {
                //得到页面传递过来的数据
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                User user = service.loginUser(username, password);

                request.getSession().setAttribute("user",user);
                request.getRequestDispatcher("/client/head.jsp").forward(request, response);

            } catch (Exception e) {
                request.setAttribute("message", "登陆失败了!");
                request.getRequestDispatcher("/message.jsp").forward(request, response);
            }

        } else if (method.equals("register")) {

            try {
                //得到JSP传递过来的数据,封装成Bean对象
                User user = WebUtils.request2Bean(request, User.class);
                user.setId(WebUtils.makeId());

                service.registerUser(user);

                request.setAttribute("message", "注册成功了!");

            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("message", "注册失败了!");
            }
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        } else if (method.equals("Logout")) {

            //销毁session
            request.getSession().invalidate();

            //回到首页
            request.getRequestDispatcher("/client/head.jsp").forward(request, response);

        }
购买模块

在显示图书的时候,顺便添加购买的超链接

    <li><a href="#">购买</a></li>
设计购物车实体

如果不清楚为什么这样设计,可参考我之前的博文:http://blog.csdn.net/hon_3y/article/details/56481439#t5

  • Cart实体

public class Cart {

    private Map<String, CartItem> map = new HashMap<>();
    private double price;

    //提供把商品添加到购物的功能
    public void addBook2Cart(Book book) {

        //得到对应的购物项
        CartItem cartItem = map.get(book.getId());

        //如果是null,说明购物车还没有该购物项
        if (cartItem == null) {
            cartItem = new CartItem();
            cartItem.setQuantity(1);
            cartItem.setBook(book);
            cartItem.setPrice(book.getPrice());

            //把购物项加到购物车中
            map.put(book.getId(), cartItem);
        } else {

            //如果购物车有该购物项了,那么将购物项的数量+1
            cartItem.setQuantity(cartItem.getQuantity() + 1);
        }
    }

    //购物车的价钱是购物项价钱的总和
    public double getPrice() {

        double totalPrice = 0;
        for (Map.Entry<String, CartItem> me : map.entrySet()) {
            CartItem cartItem = me.getValue();
            totalPrice += cartItem.getPrice();
        }

        return totalPrice;
    }

    public Map<String, CartItem> getMap() {
        return map;
    }

    public void setMap(Map<String, CartItem> map) {
        this.map = map;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}
设计购物项实体

public class CartItem {

    private Book book;
    private double price;
    private int quantity;

    public double getPrice() {
        return this.book.getPrice() * this.quantity;
    }

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

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }
    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}
处理用户想要买的书籍Servlet
    <li><a href="${pageContext.request
.contextPath}/BuyServlet?book_id=${book.id}">购买</a></li>
  • BuyServlet

        BussinessServiceImpl service = new BussinessServiceImpl();

        //先检查该用户是否登陆了。
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            request.setAttribute("message", "您还没登陆,请登陆了再来购买");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return ;
        }

        //如果登陆了...

        //得到该用户的购物车
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
            request.getSession().setAttribute("cart", cart);
        }

        //得到用户想买的书籍
        String book_id = request.getParameter("book_id");
        Book book = service.findBook(book_id);

        //把书籍添加到购物车中
        service.buyBook(cart, book);
        request.setAttribute("message", "该商品已添加到购物车中");
        request.getRequestDispatcher("/message.jsp").forward(request,response);
提供显示购物车商品的Servlet

        //先判断该用户是否登陆了
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            request.setAttribute("message", "您还没有登陆呢!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
        }

        //如果登陆了.....
        Cart cart = (Cart) request.getSession().getAttribute("cart");

        //把该用户的购物车给JSP页面显示
        request.setAttribute("cart", cart);
        request.getRequestDispatcher("/client/listCart.jsp").forward(request, response);
显示购物车的JSP页面

<c:if test="${empty(cart.map)}">

    您还没有购买过任何商品哦!!!
</c:if>

<table border="1px">
    <c:if test="${!empty(cart.map)}">
        <h1>您购物车下有如下的商品:</h1><br>

        <tr>
            <td>书名:</td>
            <td>作者:</td>
            <td>数量:</td>
            <td>价钱:</td>
        </tr>
        <c:forEach items="${cart.map}" var="cartItme">

            <tr>
                <td>${cartItme.value.book.name}</td>
                <td>${cartItme.value.book.author}</td>
                <td>${cartItme.value.quantity}</td>
                <td>${cartItme.value.price}</td>
            </tr>
        </c:forEach>

    </c:if>
</table>

效果:

这里写图片描述


点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消