zoukankan      html  css  js  c++  java
  • (六)简单验证和复杂验证

    BookServlet.java

    package com.aff.bookstore.servlet;
    
    import java.io.IOException;
    import java.lang.reflect.Method;
    import java.util.HashMap;
    import java.util.Map;
    
    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 com.aff.bookstore.domain.Account;
    import com.aff.bookstore.domain.Book;
    import com.aff.bookstore.domain.ShoppingCart;
    import com.aff.bookstore.domain.ShoppingCartItem;
    import com.aff.bookstore.domain.User;
    import com.aff.bookstore.service.AccountService;
    import com.aff.bookstore.service.BookService;
    import com.aff.bookstore.service.UserService;
    import com.aff.bookstore.web.BookStoreWebUtils;
    import com.aff.bookstore.web.CriteriaBook;
    import com.aff.bookstore.web.Page;
    import com.google.gson.Gson;
    
    @WebServlet("/bookServlet")
    public class BookServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request, response);
        }
    
        private BookService bookService = new BookService();
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String methodName = request.getParameter("method");
            try {
                Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
                        HttpServletResponse.class);
                method.setAccessible(true);
                method.invoke(this, request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private UserService userService = new UserService();
    
        protected void cash(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 1.简单验证:验证表单域的值是否符合基本的规范:是否为空,是否可以转为int类型,是否是一个email
            // 数据库或调用任何的业务方法
    
            String username = request.getParameter("username");
            String accountId = request.getParameter("accountId");
    
            // 表单验证通过
            StringBuffer errors = validateFormField(username, accountId);
            if (errors.toString().equals("")) {// 第一个验证过后验证第二个
                errors = validateUser(username, accountId);
    
                // 用户名验证通过
                if (errors.toString().equals("")) {// 第二个验证过了再验证第三个
                    errors = validateBookStoreNumber(request);
    
                    // 库存验证通过
                    if (errors.toString().equals("")) {// 验证第三个
    
                        // 验证余额是否充足
                        errors = vailidateBalance(request, accountId);
    
                    }
                }
            }
    
            // error不等于空说明得打印错误信息,则验证没通过
            if (!errors.toString().equals("")) {
                request.setAttribute("errors", errors);
                request.getRequestDispatcher("/WEB-INF/pages/cash.jsp").forward(request, response);
                return;
            }
    
        }
    
        private AccountService accountService = new AccountService();
    
        // 验证余额是否充足
        private StringBuffer vailidateBalance(HttpServletRequest request, String accountId) {
            StringBuffer errors = new StringBuffer("");
            ShoppingCart cart = BookStoreWebUtils.getShoppingCart(request);
    
            Account account = accountService.getAccount(Integer.parseInt(accountId));
            if (cart.getTotalMoney() > account.getBalance()) {
                errors.append("余额不足");
    
            }
            return errors;
        }
    
        // 验证库存是否充足
        private StringBuffer validateBookStoreNumber(HttpServletRequest request) {
            StringBuffer errors = new StringBuffer("");
            ShoppingCart cart = BookStoreWebUtils.getShoppingCart(request);
            for (ShoppingCartItem sci : cart.getItems()) {
                int quantity = sci.getQuantity();
    
                // 书的库存,获取一个最新的书的库存
                int storeNumber = bookService.getBook(sci.getBook().getId()).getStoreNumber();
    
                if (quantity > storeNumber) {
                    errors.append(sci.getBook().getTitle() + "库存不足<br>");
                }
            }
            return errors;
        }
    
        // 抽出的验证用户名和账户是否匹配
        private StringBuffer validateUser(String username, String accountId) {
            boolean flag = false;
            User user = userService.getUserByUserName(username);
            if (user != null) {
                int accountId2 = user.getAccountId();
                if (accountId.trim().equals("" + accountId2)) {
                    flag = true;
    
                }
            }
            StringBuffer errors2 = new StringBuffer("");
            if (!flag) {
                errors2.append("用户名和账户不匹配");
            }
            return errors2;
        }
    
        // 抽出的简单验证,,表单是否符合基本的规则,是否为空
        private StringBuffer validateFormField(String username, String accountId) {
            StringBuffer errors = new StringBuffer();
    
            if (username == null || username.trim().equals("")) {
                errors.append("用户名不能为空<br>");
    
            }
            if (accountId == null || accountId.trim().equals("")) {
                errors.append("账户不能为空");
            }
            return errors;
        }
    
        protected void updateItemQuantity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //4. 在 updateItemQuantity 方法中, 获取 quanity, id, 再获取购物车对象, 调用 service 的方法做修改
            System.out.println("============================");
            String idStr = request.getParameter("id");
            String quantityStr = request.getParameter("quantity");
            
            ShoppingCart sc = BookStoreWebUtils.getShoppingCart(request);
            
            int id = -1;
            int quantity = -1;
            
            try {
                id = Integer.parseInt(idStr);
                quantity = Integer.parseInt(quantityStr);
            } catch (Exception e) {}
            
            if(id > 0 && quantity > 0)
                bookService.updateItemQuantity(sc, id, quantity);
            
            //5. 传回 JSON 数据: bookNumber:xx, totalMoney
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("bookNumber", sc.getBookNumber());
            result.put("totalMoney", sc.getTotalMoney());
            
            Gson gson = new Gson();
            String jsonStr = gson.toJson(result);
            response.setContentType("text/javascript");
            response.getWriter().print(jsonStr);
        }
    
        protected void clear(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            ShoppingCart sc = BookStoreWebUtils.getShoppingCart(request);
            bookService.clearShoppingCart(sc);
            request.getRequestDispatcher("/WEB-INF/pages/empty.jsp").forward(request, response);
        }
    
        // 删除商品
        protected void remove(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String idStr = request.getParameter("id");
            int id = -1;
            try {
                id = Integer.parseInt(idStr);
            } catch (Exception e) {
            }
            ShoppingCart sc = BookStoreWebUtils.getShoppingCart(request);
            bookService.removeItemFromShoppingCart(sc, id);
            if (sc.isEmpty()) {
                request.getRequestDispatcher("/WEB-INF/pages/empty.jsp").forward(request, response);
            }
    
            // 删除完再转发为回来
            request.getRequestDispatcher("/WEB-INF/pages/cart.jsp").forward(request, response);
    
        }
    
        protected void forwardPage(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String page = request.getParameter("page");
            request.getRequestDispatcher("/WEB-INF/pages/" + page + ".jsp").forward(request, response);
        }
    
        protected void addToCart(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            // 1.获取商品的id
            String idStr = request.getParameter("id");
            int id = -1;
            boolean flag = false;
    
            try {
                id = Integer.parseInt(idStr);
            } catch (Exception e) {
            }
    
            if (id > 0) {
                // 2.获取购物差对象
                ShoppingCart sc = BookStoreWebUtils.getShoppingCart(request);
    
                // 3.调用 BookService 的addToCart() 方法 把商品放到购物车中
                flag = bookService.addToCart(id, sc);
            }
    
            if (flag) {
                // 4.直接调用 getBooks()方法
                getBooks(request, response);
                return;
            }
            response.sendRedirect(request.getContextPath() + "/errror-1.jsp");
        }
    
        protected void getBook(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String idStr = request.getParameter("id");
            int id = -1;
            Book book = null;
    
            try {
                id = Integer.parseInt(idStr);
            } catch (NumberFormatException e) {
            }
    
            if (id > 0) {
                book = bookService.getBook(id);
                if (book == null) {
                    response.sendRedirect(request.getContextPath() + "/errror-1.jsp");
                    return;
                }
            }
            request.setAttribute("book", book);
            request.getRequestDispatcher("/WEB-INF/pages/book.jsp").forward(request, response);
        }
    
        protected void getBooks(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String pageNoStr = request.getParameter("pageNo");
            String minPriceStr = request.getParameter("minPrice");
            String maxPriceStr = request.getParameter("maxPrice");
    
            int pageNo = 1;
            int minPrice = 0;
            int maxPrice = Integer.MAX_VALUE;
            try {
                pageNo = Integer.parseInt(pageNoStr);
            } catch (Exception e) {
            }
            try {
                minPrice = Integer.parseInt(minPriceStr);
            } catch (Exception e) {
            }
            try {
                maxPrice = Integer.parseInt(maxPriceStr);
            } catch (Exception e) {
            }
            CriteriaBook criteriaBook = new CriteriaBook(minPrice, maxPrice, pageNo);
            Page<Book> page = bookService.getPage(criteriaBook);
    
            request.setAttribute("bookpage", page);
            request.getRequestDispatcher("/WEB-INF/pages/books.jsp").forward(request, response);
    
        }
    
    }

    cash.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "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>
                <center>
                        <br><br>
                        您一共买了 ${sessionScope.ShoppingCart.bookNumber} 本书
                        <br><br>
                        应付:¥${sessionScope.ShoppingCart.totalMoney}
                        <br><br>
                        
                        <c:if test="${requestScope.errors !=null }">
                        <font color="red">${requestScope.errors }</font>
                        
                        
                        </c:if>
                        
                
                <form action="bookServlet?method=cash" method="post">
                <table cellpadding="10">
                        <tr>
                                <td>信用卡姓名</td>
                                <td><input type="text" name="username"/></td>
                        </tr>
                        <tr>
                                <td>信用卡账号</td>
                                <td><input type="text" name="accountId"/></td>
                        </tr>
                        <tr>
                                <td colspan="2"><input type="submit" value="Submit"/></td>
                        </tr>
                </table>
                
                </form>
                </center>
                
    </body>
    </html>

    效果如下

    All that work will definitely pay off
  • 相关阅读:
    2、selinux服务的操作
    1、添加nginx到全局变量中
    linux每日命令(1):which
    QT重载基类绘制函数并在基类绘制结果基础上进行子类的绘制
    QT信号槽无法正常通信的原因
    mapgis6.7+加密狗+二次开发SDK库
    KMP算法参考及C语言实现
    elastic search
    RabbitMq docker集群
    RabbitMq安装
  • 原文地址:https://www.cnblogs.com/afangfang/p/12922954.html
Copyright © 2011-2022 走看看