jsp+servlet實戰編寫購物商城

點贊再看,養成習慣javascript

項目介紹

本項目使用jsp+servlet+mysql架構搭建美妝購物商城,主要分爲用戶端和商城端,用戶端主要有首頁展現,商品信息、購物車、訂單和我的中心幾個大的模塊,每一個模塊都包含主要的電商功能;商戶端主要是對商品的增刪改查,對商品銷量的統計,訂單管理以及公告管理幾個核心板塊。java

開發環境:

  1. jdk 8
  2. intellij idea
  3. tomcat 8
  4. mysql 5.7

所用技術:

  1. jsp+servlet
  2. js+ajax
  3. layui
  4. jdbc+C3P0

運行效果

  • 註冊

註冊

  • 用戶信息

用戶信息

  • 首頁

首頁

  • 商品列表

商品列表

  • 訂單確認

訂單確認

  • 後端-銷售榜單

jsp+servlet實戰編寫購物商城

重要代碼:

  1. 登陸,權限角色控制:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 1.獲取登陸頁面輸入的用戶名與密碼
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    // 2.調用service完成登陸操做。
    UserService service = new UserService();
    try {
        User user = service.login(username, password);
        // 3.登陸成功,將用戶存儲到session中.
        request.getSession().setAttribute("user", user);
        // 獲取用戶的角色,其中用戶的角色分普通用戶和超級用戶兩種
        String role = user.getRole();
        // 若是是超級用戶,就進入到後臺管理系統;不然進入個人帳戶頁面
        if ("超級用戶".equals(role)) {
            response.sendRedirect(request.getContextPath() + "/admin/login/home.jsp");
            return;
        } else {
            response.sendRedirect(request.getContextPath() + "/client/myAccount.jsp");
            return;
        }
    } catch (LoginException e) {
        // 若是出現問題,將錯誤信息存儲到request範圍,並跳轉回登陸頁面顯示錯誤信息
        e.printStackTrace();
        request.setAttribute("register_message", e.getMessage());
        request.getRequestDispatcher("/client/login.jsp").forward(request, response);
        return;
    }
}
// 退出登陸,銷燬用戶緩存信息
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    // 獲取session對象.
    HttpSession session = request.getSession();     
     // 銷燬session
    session.invalidate();
     // flag標識
    String flag = request.getParameter("flag");     
      // 重定向到首頁
    if (flag == null || flag.trim().isEmpty()) {
        response.sendRedirect(request.getContextPath() + "/index.jsp");
    }
}
  1. 購物車邏輯
// 後端數據組裝
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    // 1.獲取美妝id
    String id = request.getParameter("id");
    // 2.根據id條件查詢具體美妝參數信息
    ProductService service = new ProductService();
    try {
        Product p = service.findProductById(id);
        //3.將商品添加到購物車
        //3.1得到session對象
        HttpSession session = request.getSession();
        //3.2從session中獲取購物車對象
        Map<Product, Integer> cart = (Map<Product, Integer>)session.getAttribute("cart");
        //3.3若是購物車爲null,說明沒有商品存儲在購物車中,建立出購物車
        if (cart == null) {
            cart = new HashMap<Product, Integer>();
        }
        //3.4向購物車中添加商品
        Integer count = cart.put(p, 1);
        //3.5若是商品數量不爲空,則商品數量+1,不然添加新的商品信息
        if (count != null) {
            cart.put(p, count + 1);
        }           
        session.setAttribute("cart", cart);
        response.sendRedirect(request.getContextPath() + "/client/cart.jsp");
        return;
    } catch (FindProductByIdException e) {
        e.printStackTrace();
    }
}

//jsp 頁面數據渲染
<c:forEach items="${cart}" var="entry" varStatus="vs">
    <table width="100%" border="0" cellspacing="0">
        <tr>
            <td width="10%">${vs.count}</td>
            <td width="30%">${entry.key.name }</td>
            <td width="10%">${entry.key.price }</td>
            <td width="20%">
                <!-- 減小商品數量 -->
                <input type="button" value='-' style="width:20px"
                       onclick="changeProductNum('${entry.value-1}','${entry.key.pnum}','${entry.key.id}')">
                 <!-- 商品數量顯示 -->
                <input name="text" type="text" value="${entry.value}" style="width:40px;text-align:center" />
                <!-- 增長商品數量 -->
                <input type="button" value='+' style="width:20px"
                       onclick="changeProductNum('${entry.value+1}','${entry.key.pnum}','${entry.key.id}')">
            </td>
            <td width="10%">${entry.key.pnum}</td>
            <td width="10%">${entry.key.price*entry.value}</td>
            <td width="10%">
                <!-- 刪除商品 -->
                <a href="${pageContext.request.contextPath}/changeCart?id=${entry.key.id}&count=0"
                style="color:#FF0000; font-weight:bold" onclick="javascript:return cart_del()">X</a>
            </td>
        </tr>
    </table>
    <c:set value="${total+entry.key.price*entry.value}" var="total" />
</c:forEach>
  1. 文字驗證碼生成

文字驗證碼生成

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    // 禁止緩存
    // response.setHeader("Cache-Control", "no-cache");
    // response.setHeader("Pragma", "no-cache");
    // response.setDateHeader("Expires", -1);
    int width = 180;
    int height = 30;
    // 步驟一 繪製一張內存中圖片
    BufferedImage bufferedImage = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);
    // 步驟二 圖片繪製背景顏色 ---經過繪圖對象
    Graphics graphics = bufferedImage.getGraphics();// 獲得畫圖對象 --- 畫筆
    // 繪製任何圖形以前 都必須指定一個顏色
    graphics.setColor(getRandColor(200, 250));
    graphics.fillRect(0, 0, width, height);
    // 步驟三 繪製邊框
    graphics.setColor(Color.WHITE);
    graphics.drawRect(0, 0, width - 1, height - 1);
    // 步驟四 四個隨機數字
    Graphics2D graphics2d = (Graphics2D) graphics;
    // 設置輸出字體
    graphics2d.setFont(new Font("宋體", Font.BOLD, 18));
    Random random = new Random();// 生成隨機數
    int index = random.nextInt(words.size());
    String word = words.get(index-1);// 得到成語
    // 定義x座標
    int x = 10;
    for (int i = 0; i < word.length(); i++) {
        // 隨機顏色
        graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random
                .nextInt(110), 20 + random.nextInt(110)));
        // 旋轉 -30 --- 30度
        int jiaodu = random.nextInt(60) - 30;
        // 換算弧度
        double theta = jiaodu * Math.PI / 180;
        // 得到字母數字
        char c = word.charAt(i);
        // 將c 輸出到圖片
        graphics2d.rotate(theta, x, 20);
        graphics2d.drawString(String.valueOf(c), x, 20);
        graphics2d.rotate(-theta, x, 20);
        x += 40;
    }
    // 將驗證碼內容保存session
    request.getSession().setAttribute("checkcode_session", word);
    // 步驟五 繪製干擾線
    graphics.setColor(getRandColor(160, 200));
    int x1;
    int x2;
    int y1;
    int y2;
    for (int i = 0; i < 30; i++) {
        x1 = random.nextInt(width);
        x2 = random.nextInt(12);
        y1 = random.nextInt(height);
        y2 = random.nextInt(12);
        graphics.drawLine(x1, y1, x1 + x2, x2 + y2);
    }
    // 將上面圖片輸出到瀏覽器 ImageIO
    graphics.dispose();// 釋放資源
    ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}

項目總結

經過項目能學習一些java的基本數據渲染和讀取,先後端數據傳遞除開request外也能夠用session進行緩存交互,可是有點浪費緩存資源,沒必要要長久緩存數據能夠及時清空
緩存,原生jsp+servlet組合框架也有不少不足,後期會改版成ssh或者ssm或者springboot版本的電商平臺mysql

相關文章
相關標籤/搜索