Java 项目控制层测试

登录

代码如下

package net.lh.shop.servlet;

/**
 * 功能:登录处理类
 * 作者:刘浩
 * 日期:2019年12月9日
 */

import java.io.IOException;

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 net.lh.shop.bean.User;
import net.lh.shop.service.UserService;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求对象的字符编码l
        request.setCharacterEncoding("utf-8");
        // 获取会话对象
        HttpSession session = request.getSession();
        // 获取用户名
        String username = request.getParameter("username");
        // 获取密码
        String password = request.getParameter("password");
        // 定义用户服务对象
        UserService userService = new UserService();
        // 执行登录方法,返回用户实体
        User user = userService.login(username, password);
        // 判断用户登录是否成功
        if (user != null) {
            // 设置session属性
            session.setMaxInactiveInterval(5 * 60);
            session.setAttribute("username", username);
            session.removeAttribute("loginMsg");
            // 根据用户权限跳转到不同页面
            if (user.getPopedom() == 0) {
                System.out.println("用户登录成功,进入后台管理!");
                response.sendRedirect(request.getContextPath() + "/backend/management.jsp");
            } else if (user.getPopedom() == 1) {
                System.out.println("用户登录成功,进入前台显示类别!");
                response.sendRedirect(request.getContextPath() + "/showCategory");
            }
        } else {
            System.out.println("用户名或密码错误,用户登录失败!");
            // 设置session属性loginMsg
            session.setAttribute("loginMsg", "用户名或密码错误!");
            response.sendRedirect(request.getContextPath() + "/login.jsp");
    }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

测试
管理员登录Java 项目控制层测试_第1张图片
Java 项目控制层测试_第2张图片Java 项目控制层测试_第3张图片
普通用户登录
Java 项目控制层测试_第4张图片
Java 项目控制层测试_第5张图片

Java 项目控制层测试_第6张图片

登录失败

Java 项目控制层测试_第7张图片
Java 项目控制层测试_第8张图片
Java 项目控制层测试_第9张图片

注销

代码如下


```java
package net.lh.shop.servlet;

/**
 * 功能:注销处理类
 * 作者:刘浩
 * 日期:2019年12月9日
 */

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 让session失效
        request.getSession().invalidate();
        // 重定向到登录页面
        System.out.print("用户注销成功!");
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}


测试注销要先登录
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209120216922.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209115906248.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)输入 localhost:8080/simonshop/logout

![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209115846494.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)


![在这里插入图片描述](https://img-blog.csdnimg.cn/2019120912005144.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)

## 注册

```java

```java
package net.lh.shop.servlet;

/**
 * 功能:处理用户注册
 * 作者:刘浩
 * 日期:2019年12月5日
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Timestamp;

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 net.lh.shop.bean.User;
import net.lh.shop.service.UserService;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求对象的字符编码
        request.setCharacterEncoding("utf-8");
        // 获取session对象
        HttpSession session = request.getSession();

        // 获取用户名
        String username = request.getParameter("username");
        // 获取密码
        String password = request.getParameter("password");
        // 获取电话号码
        String telephone = request.getParameter("telephone");
        // 设置注册时间(时间戳对象)
        Timestamp registerTime = new Timestamp(System.currentTimeMillis());
        // 设置用户为普通用户
        int popedom = 1;

        // 创建用户对象
        User user = new User();
        // 设置用户对象信息
        user.setUsername(username);
        user.setPassword(password);
        user.setTelephone(telephone);
        user.setRegisterTime(registerTime);
        user.setPopedom(popedom);

        // 创建UserService对象
        UserService userService = new UserService();
        // 调用UserService对象的注册方法
        int count = userService.addUser(user);

        // 判断是否注册成功
        if (count > 0) {
            // 设置session属性
            session.setAttribute("registerMsg", "恭喜,注册成功!");
            // 重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            //在控制台输出测试信息
            System.out.println("恭喜,注册成功,跳转到登录页面!");
        } else {
            // 设置session属性
            session.setAttribute("registerMsg", "遗憾,注册失败!");
            // 重定向到注册页面
            response.sendRedirect(request.getContextPath() + "/frontend/register.jsp");
            //在控制台输出测试信息
            System.out.println("遗憾,注册失败,跳转到注册页面!");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}


![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209120327705.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209120350198.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209120407400.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209120426485.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)
注册失败
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209120455960.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209120528467.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209120550413.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191209120607867.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1VuaW50ZW50aW9uYWxseQ==,size_16,color_FFFFFF,t_70)
### 显示商品类

```java
package net.lh.shop.servlet;
/**
 * 功能:显示类别控制程序
 * 作者:刘浩
 * 日期:2019年12月9日
 */

import java.io.IOException;
import java.util.List;

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 net.lh.shop.bean.Category;
import net.lh.shop.service.CategoryService;



@WebServlet("/showCategory")
public class ShowCategoryServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 创建类别服务对象
        CategoryService categoryService = new CategoryService();
        // 获取全部商品类别
        List categories = categoryService.findAllCategories();
        // 获取session对象
        HttpSession session = request.getSession();
        // 把商品类别列表以属性的方式保存到session里
        session.setAttribute("categories", categories);
        // 重定向到显示商品类别页面(showCategory.jsp)
        response.sendRedirect(request.getContextPath() + "/frontend/showCategory.jsp");
        //服务器端控制台输出测试信息
        for (Category category : categories){
            System.out.println(category);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}


Java 项目控制层测试_第10张图片
Java 项目控制层测试_第11张图片
Java 项目控制层测试_第12张图片

显示商品名

package net.lh.shop.servlet;


/**
 * 功能:显示商品列表的控制程序
 *     通过业务层访问后台数据,
 *     然后将数据返回给前台页面
 * 作者:刘浩
 * 日期:2019年12月9日
 */



import java.io.IOException;

import java.util.List;

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 net.lh.shop.bean.Product;
import net.lh.shop.service.CategoryService;
import net.lh.shop.service.ProductService;

@WebServlet("/showProduct")
public class ShowProductServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取类别标识符
        int categoryId = Integer.parseInt(request.getParameter("categoryId"));
        // 创建商品类别服务对象
        CategoryService categoryService = new CategoryService();
        // 由类别标识符获取类别名
        String categoryName = categoryService.findCategoryById(categoryId).getName();

        // 创建商品服务对象
        ProductService productService = new ProductService();
        // 获取指定商品类别的商品列表
        List<Product> products = productService.findProductsByCategoryId(categoryId);
        // 获取session对象
        HttpSession session = request.getSession();

        // 把商品列表对象以属性的方式保存到session里
        session.setAttribute("products", products);

        // 重定向到显示商品信息页面
        response.sendRedirect(request.getContextPath() + "/frontend/showProduct.jsp?categoryName=" + categoryName);
        // 服务器端控制台输出测试信息
        for(int i = 0; i < products.size(); i++){
            System.out.println(products.get(i));
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

Java 项目控制层测试_第13张图片
Java 项目控制层测试_第14张图片Java 项目控制层测试_第15张图片

显示购物车处理类(ShowCartServlet)

代码:

package net.lh.shop.servlet;

/**
 * 功能:显示购物车控制程序
 * 作者:刘浩
 * 日期:2019年12月16日
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

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 net.lh.shop.bean.Product;
import net.lh.shop.service.ProductService;

@WebServlet("/showCart")
public class ShowCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取商品类别标识符
        int categoryId = Integer.parseInt(request.getParameter("categoryId"));
        // 获取session对象
        HttpSession session = request.getSession();
        // 获取购物车
        LinkedHashMap<Integer, Integer> cart = (LinkedHashMap<Integer, Integer>) session.getAttribute("cart");

        // 判断购物车是否为空
        if (cart != null) {
            // 定义购物表
            List<HashMap<String, Object>> shoppingTable = new ArrayList<HashMap<String, Object>>();
            // 创建商品服务对象
            ProductService productService = new ProductService();
            // 购物总金额
            double totalPrice = 0.0;
            // 遍历购物车
            for (Integer id : cart.keySet()) {
                // 获取商品对象
                Product product = productService.findProductById(id);
                // 生成购物表记录
                HashMap<String, Object> shoppingItem = new HashMap<String, Object>();
                shoppingItem.put("id", product.getId());
                shoppingItem.put("name", product.getName());
                shoppingItem.put("price", product.getPrice());
                shoppingItem.put("amount", cart.get(id));
                shoppingItem.put("sum", product.getPrice() * cart.get(id));
                // 将购物表记录添加到购物表中
                shoppingTable.add(shoppingItem);
                // 累加购买总金额
                totalPrice = totalPrice + (Double) shoppingItem.get("sum");
            }

            // 将购物表和购买总金额保存到session里
            session.setAttribute("shoppingTable", shoppingTable);
            session.setAttribute("totalPrice", totalPrice);

            // 重定向到显示商品控制程序
            response.sendRedirect(request.getContextPath() + "/showProduct?categoryId=" + categoryId);
        } else {
            System.out.println("购物车里没有类别号为[" + categoryId + "]的商品!");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

开始测试
重启服务器访问 http://localhost:8080/simonshop/showCart?categoryId=1

Java 项目控制层测试_第16张图片
我们去控制台查看信息
Java 项目控制层测试_第17张图片

操作购物车处理类(OperateCartServlet)

package net.lh.shop.servlet;


/**
 * 功能:操作购物车控制程序
 * 作者:刘浩
 * 日期:2019年12月16日
 */

import java.io.IOException;
import java.util.LinkedHashMap;

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 net.lh.shop.service.ProductService;

@WebServlet("/operateCart")
public class OperateCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取商品标识符
        int id = Integer.parseInt(request.getParameter("id"));
        // 获取商品操作
        String operation = request.getParameter("operation");

        // 从session里获取购物车(键:商品标识符;值:购买数量)
        LinkedHashMap<Integer, Integer> cart = (LinkedHashMap<Integer, Integer>) request.getSession()
                .getAttribute("cart");
        // 判断购物车是否为空
        if (cart == null) {
            // 创建购物车
            cart = new LinkedHashMap<Integer, Integer>();
            // 将购物车保存到session里,便于用户在不同页面访问购物车
            request.getSession().setAttribute("cart", cart);
        }

        if (operation.equals("add")) {
            // 将商品添加到购物车
            if (cart.containsKey(id)) { // 该商品已购买过
                // 购买数量增加1
                cart.put(id, cart.get(id) + 1);
            } else { // 该商品未曾购买
                // 购买数量设置为1
                cart.put(id, 1);
            }
        } else if (operation.equals("delete")){
            // 将商品从购物车删除
            if (cart.get(id) > 1) {
                // 购买数量减少1
                cart.put(id, cart.get(id) - 1);
            } else {
                // 从购物车里删除该商品
                cart.remove(id);
            }
        }

        // 创建商品服务对象
        ProductService productService = new ProductService();
        // 获取该商品类别标识符
        int categoryId = productService.findProductById(id).getCategoryId();
        // 重定向到显示购物车控制程序
        response.sendRedirect(request.getContextPath() + "/showCart?categoryId=" + categoryId);
    }
}

生成订单处理类(MakeOrderServlet)

package net.lh.shop.servlet;


/**
 * 功能:生成订单控制程序
 * 作者:刘浩
 * 日期:2019年12月16日
 */

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

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 net.lh.shop.bean.Order;
import net.lh.shop.bean.User;
import net.lh.shop.service.OrderService;
import net.lh.shop.service.UserService;
import net.lh.shop.service.OrderService;
import net.lh.shop.service.UserService;

@WebServlet("/makeOrder")
public class MakeOrderServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求对象的字符编码
        request.setCharacterEncoding("utf-8");
        // 获取表单提交数据
        String username = request.getParameter("username");
        String telephone = request.getParameter("telephone");
        Double totalPrice = Double.parseDouble(request.getParameter("totalPrice"));
        String deliveryAddress = request.getParameter("deliveryAddress");
        // 创建订单对象
        Order order = new Order();
        // 设置订单属性
        order.setUsername(username);
        order.setTotalPrice(totalPrice);
        order.setTelephone(telephone);
        order.setDeliveryAddress(deliveryAddress);
        order.setOrderTime(new Date());
        // 创建订单服务
        OrderService orderService = new OrderService();
        // 添加订单
        orderService.addOrder(order);
        // 获取最后一个订单
        Order lastOrder = orderService.findLastOrder();
        // 保存到session里
        request.getSession().setAttribute("lastOrder", lastOrder);
        // 重定向到显示订单页面
        response.sendRedirect(request.getContextPath() + "/frontend/showOrder.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

支付处理类(PayServlet)

package net.lh.shop.servlet;
/**
 * 功能:支付处理程序
 * 作者:刘浩
 * 日期:2019年12月16日
 */

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 java.io.IOException;

@WebServlet("/pay")
public class PayServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求对象的字符编码
        request.setCharacterEncoding("utf-8");
        ///////////////////////
        // 待做部分
        // 设置session失效
        request.getSession().invalidate();
        // 重定向到登录页面
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

显示用户处理类(ShowUserServlet)

package net.lh.shop.servlet;


/**
 * 功能:显示用户控制程序
 * 作者:刘浩
 * 日期:2019年12月14日
 */

import java.io.IOException;
import java.util.List;

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 net.lh.shop.bean.User;
import net.lh.shop.service.UserService;

@WebServlet("/showUser")
public class ShowUserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 创建用户服务对象
        UserService userService = new UserService();
        // 获取全部用户
        List<User> users = userService.findAllUsers();
        // 获取session对象
        HttpSession session = request.getSession();
        // 把用户列表以属性的方式保存到session里
        session.setAttribute("users", users);
        // 重定向到显示用户页面(showUser.jsp)
        response.sendRedirect(request.getContextPath() + "/backend/showUser.jsp");
        // 在控制台输出所有用户信息
        for (User user: users) {
            System.out.println(user);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

重启服务器输入 http://localhost:8080/simonshop/showUser

Java 项目控制层测试_第18张图片

Java 项目控制层测试_第19张图片
我们到服务器控制台查看信息
Java 项目控制层测试_第20张图片

你可能感兴趣的:(Java 项目控制层测试)