目录
1、登陆用户名的显示
2、用户的登出
3、用户注册验证码功能的实现
4、验证码的切换
5、购物车模块的实现
6、加入购物车功能的实现
7、购物车页面的显示
8、购物车删除商品功能的实现
9、清空购物车功能的实现
10、修改购物车的商品数量
11、购物车添加商品的回显
UserServlet程序中保存用户的登陆信息
protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1 获取请求的参数 String username = req.getParameter("username"); String password = req.getParameter("password"); // 2 调用UserService业务查询 User loginUser = userService.login(username, password); if(loginUser == null) { // 返回值为null,登陆失败 //回写错误信息和用户名 req.setAttribute("msg","用户名或密码错误!"); req.setAttribute("username",username); // 跳转回登录页面 req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp); } else { // 返回值不为null,登陆成功 // 保存用户的登陆信息到session域中 req.getSession().setAttribute("user",loginUser); // 跳转到登陆成功页面 req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp); } }
修改登陆成功菜单显示数据(login_success_menu.jsp)
<div> <span>欢迎<span class="um_span">${sessionScope.user.username}</span>光临尚硅谷书城</span> <a href="pages/order/order.jsp">我的订单</a> <a href="index.jsp">注销</a> <a href="index.jsp">返回</a> </div>
修改登陆成功后首页显示数据(index.jsp)
<div> <%--如果登陆未成功,显示【登陆】【注册】菜单--%> <c:if test="${empty sessionScope.user}"> <a href="pages/user/login.jsp">登录</a> | <a href="pages/user/regist.jsp">注册</a> </c:if> <%--如果登陆成功,显示【我的订单】【注销】菜单--%> <c:if test="${not empty sessionScope.user}"> <span>欢迎<span class="um_span">${sessionScope.user.username}</span>光临尚硅谷书城</span> <a href="pages/order/order.jsp">我的订单</a> <a href="index.jsp">注销</a> </c:if> <a href="pages/cart/cart.jsp">购物车</a> <a href="pages/manager/manager.jsp">后台管理</a> </div>
在UserServlet中添加logout方法
/** * 登出/账户注销功能 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1 销毁Session/清楚Session域中的用户信息 req.getSession().invalidate(); // 2 请求重定向 resp.sendRedirect(req.getContextPath()); }
2、修改注销菜单的提交地址
<a href="userServlet?action=logout">注销</a>
导入谷歌浏览器生成验证码的jar包
在web.xml中配置KaptchaServlet
<servlet> <servlet-name>KaptchaServlet</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>KaptchaServlet</servlet-name> <url-pattern>/kaptcha.jpg</url-pattern> </servlet-mapping>
在注册页面显示验证码
<label>验证码:</label> <input class="itxt" type="text" style="width: 120px;" name="code" id="code"/> <img alt="" src="kaptcha.jpg" style="width: 100px; height:40px;float: right;margin-right: 40px">
在UserServlet中regist方法编写代码
protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取Session域中的验证码 String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY); // 删除Session域中的验证码 req.getSession().removeAttribute(KAPTCHA_SESSION_KEY); // 1 获取参数 String username = req.getParameter("username"); String password = req.getParameter("password"); String email = req.getParameter("email"); String code = req.getParameter("code"); User user = new User(); WebUtils.copyParamToBean(req.getParameterMap(),user); // 2 校验验证码 if(token != null && token.equalsIgnoreCase(code)) { // 验证码正确 // 3 验证用户名是否存在 if(userService.existsUsername(username)) { // 用户名不可用 System.out.println("用户名不可用"); //回写错误信息 req.setAttribute("msg","用户名已存在"); req.setAttribute("username",username); req.setAttribute("email",email); // 跳转回注册页面 req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp); } else { // 用户名可用 // 保存注册信息 userService.registUser(new User(null,username,password,email)); // 跳转到注册成功页面 req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp); } } else { //验证码错误 System.out.println("验证码错误"); //回写错误信息 req.setAttribute("msg","验证码错误"); req.setAttribute("username",username); req.setAttribute("email",email); // 跳回注册页面 req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp); } }
给验证码标签增加id属性
<img id="code_img" alt="" src="kaptcha.jpg" style="width: 100px;height:40px;float: right; margin-right: 40px">
给验证码绑定单击事件
// 给验证码图片绑定单击事件 $("#code_img").click(function () { // this.src表示当前验证码img标签的图片路径,可读可写 // new Date()给验证码添加唯一性参数,使它可以不断更新 this.src = "${basePath}kaptcha.jpg?d=" + new Date(); });
CartItem的编写
package pojo; import java.math.BigDecimal; /** * @description:购物车的商品项 * @create 2022-01-19 20:28 */ public class CartItem { private Integer id; private String name; private Integer count; private BigDecimal price; private BigDecimal totalPrice; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getTotalPrice() { return totalPrice; } public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; } public CartItem() { } public CartItem(Integer id, String name, Integer count, BigDecimal price, BigDecimal totalPrice) { this.id = id; this.name = name; this.count = count; this.price = price; this.totalPrice = totalPrice; } @Override public String toString() { return "CartItem{" + "id=" + id + ", name='" + name + '\'' + ", count=" + count + ", price=" + price + ", totalPrice=" + totalPrice + '}'; } }
Cart的编写
package pojo; import java.math.BigDecimal; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * @description:购物车对象 * @create 2022-01-19 20:32 */ public class Cart { // private Integer totalCount; // private BigDecimal totalPrice; private Map<Integer,CartItem> items = new LinkedHashMap<Integer,CartItem>(); public Integer getTotalCount() { Integer totalCount = 0; // 遍历购物车中所有商品 for (Map.Entry<Integer,CartItem> entry:items.entrySet()) { totalCount += entry.getValue().getCount();// 累加所有的商品数量 } return totalCount; } public BigDecimal getTotalPrice() { BigDecimal totalPrice = new BigDecimal(0); // 遍历购物车中所有商品 for (Map.Entry<Integer,CartItem> entry:items.entrySet()) { totalPrice = totalPrice.add(entry.getValue().getTotalPrice());// 累加所有的商品数量 } return totalPrice; } public Map<Integer, CartItem> getItems() { return items; } public void setItems(Map<Integer, CartItem> items) { this.items = items; } /** * 增加商品的方法 * @param cartItem */ public void addItem(CartItem cartItem) { //判断当前商品是否在购物车中,如果有,改变商品的数量和总价;如果没有,则添加进购物车中 CartItem item = items.get(cartItem.getId()); if (item != null) { // 此商品已存在 item.setCount(item.getCount() + 1);//商品的数量+1 item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getCount())));//商品的总价=单价*数量 } else { // 此商品不存在 items.put(cartItem.getId(),cartItem); } } /** * 删除商品的方法 */ public void deleteItem(Integer id) { items.remove(id); } /** * 清空商品 */ public void clear( ) { items.clear(); } /** * 修改商品的数量 */ public void updateCount(Integer id,Integer count) { // 判断商品是否存在在购物车中,如果存在,则修改商品的数量,更新总金额; CartItem cartItem = items.get(id); if (cartItem != null) { cartItem.setCount(count);//修改商品的数量 cartItem.setTotalPrice(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())));//修改商品的总金额 } } @Override public String toString() { return "Cart{" + "totalCount=" + getTotalCount() + ", totalPrice=" + getTotalPrice() + ", items=" + items + '}'; } }
Cart类中方法的测试
package test; import org.junit.Test; import pojo.Cart; import pojo.CartItem; import java.math.BigDecimal; import static org.junit.Assert.*; /** * @description: * @create 2022-01-19 23:08 */ public class CartTest { @Test public void addItem() { Cart cart = new Cart(); cart.addItem(new CartItem(1,"Java从入门到精通",1,new BigDecimal(1000),new BigDecimal(1000))); cart.addItem(new CartItem(1,"Java从入门到精通",1,new BigDecimal(1000),new BigDecimal(1000))); cart.addItem(new CartItem(2,"数据结构与算法",1,new BigDecimal(100),new BigDecimal(100))); System.out.println(cart); } @Test public void deleteItem() { Cart cart = new Cart(); cart.addItem(new CartItem(1,"Java从入门到精通",1,new BigDecimal(1000),new BigDecimal(1000))); cart.addItem(new CartItem(1,"Java从入门到精通",1,new BigDecimal(1000),new BigDecimal(1000))); cart.addItem(new CartItem(2,"数据结构与算法",1,new BigDecimal(100),new BigDecimal(100))); cart.deleteItem(1); System.out.println(cart); } @Test public void clear() { Cart cart = new Cart(); cart.addItem(new CartItem(1,"Java从入门到精通",1,new BigDecimal(1000),new BigDecimal(1000))); cart.addItem(new CartItem(1,"Java从入门到精通",1,new BigDecimal(1000),new BigDecimal(1000))); cart.addItem(new CartItem(2,"数据结构与算法",1,new BigDecimal(100),new BigDecimal(100))); cart.clear(); System.out.println(cart); } @Test public void updateCount() { Cart cart = new Cart(); cart.addItem(new CartItem(1,"Java从入门到精通",1,new BigDecimal(1000),new BigDecimal(1000))); cart.addItem(new CartItem(1,"Java从入门到精通",1,new BigDecimal(1000),new BigDecimal(1000))); cart.addItem(new CartItem(2,"数据结构与算法",1,new BigDecimal(100),new BigDecimal(100))); cart.updateCount(2,2); System.out.println(cart); } }
给按钮绑定单击事件
<div class="book_add"> <button class="addToCart" bookId="${book.id}">加入购物车</button> </div>
<script type="text/javascript"> $(function () { $("button.addToCart").click(function () { var bookId = $(this).attr("bookId"); location = "${basePath}cartServlet?action=addItem&id=" + bookId; }); }); </script>
编写CartServlet类并在web.xml中配置地址
package web; import pojo.Book; import pojo.Cart; import pojo.CartItem; import service.BookService; import service.impl.BookServiceImpl; import utils.WebUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.math.BigDecimal; /** * @description: * @create 2022-01-20 10:38 */ public class CartServlet extends BaseServlet{ private BookService bookService = new BookServiceImpl(); protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取添加图书的编号 int bookid = WebUtils.parseInt(req.getParameter("id"), 0); // 根据图书编号获取图书信息 Book book = bookService.queryBookById(bookid); // 将图书信息转化成商品项 CartItem cartItem = new CartItem(book.getId(),book.getName(),1,book.getPrice(),book.getPrice()); // 调用addItem向购物车内添加商品 Cart cart = (Cart) req.getSession().getAttribute("cart"); if (cart == null) { cart = new Cart(); req.getSession().setAttribute("cart",cart); } cart.addItem(cartItem); System.out.println(cart); System.out.println("Referer:" + req.getHeader("Referer")); resp.sendRedirect(req.getHeader("Referer")); } }
<servlet> <servlet-name>CartServlet</servlet-name> <servlet-class>web.CartServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CartServlet</servlet-name> <url-pattern>/cartServlet</url-pattern> </servlet-mapping>
<div id="main"> <table> <tr> <td>商品名称</td> <td>数量</td> <td>单价</td> <td>金额</td> <td>操作</td> </tr> <%--购物车内的商品不为空--%> <c:if test="${not empty sessionScope.cart.items}"> <%--遍历输出商品--%> <c:forEach items="${sessionScope.cart.items}" var="entry"> <tr> <td>${entry.value.name}</td> <td>${entry.value.count}</td> <td>${entry.value.price}</td> <td>${entry.value.totalPrice}</td> <td><a href="#">删除</a></td> </tr> </c:forEach> </c:if> <%--购物车内的商品为空--%> <c:if test="${empty sessionScope.cart.items}"> <tr> <td colspan="5"><a href="index.jsp">当前购物车为空,赶快去选购吧</a> </td> </tr> </c:if> </table> <c:if test="${not empty sessionScope.cart.items}"> <div class="cart_info"> <span class="cart_span">购物车中共有<span class="b_count">${sessionScope.cart.totalCount}</span>件商品</span> <span class="cart_span">总金额<span class="b_price">${sessionScope.cart.totalPrice}</span>元</span> <span class="cart_span"><a href="#">清空购物车</a></span> <span class="cart_span"><a href="pages/cart/checkout.html">去结账</a></span> </div> </c:if> </div>
deleteItem方法的编写
protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取要删除的商品id int id = WebUtils.parseInt(req.getParameter("id"), 0); // 获取购物车对象 Cart cart = (Cart) req.getSession().getAttribute("cart"); if (cart != null) { // 删除购物车里的商品项 cart.deleteItem(id); // 重定向回原来的页面 resp.sendRedirect(req.getHeader("Referer")); } }
提交地址的修改
<td><a class="deleteItem" href="cartServlet?action=deleteItem&id=${entry.value.id}">删除</a></td>
确认删除功能的实现
<script type="text/javascript"> $(function () { $("a.deleteItem").click(function () { return confirm("确认要删除【" + $(this).parent().parent().find("td:first").text()+ "】吗?") }); }); </script>
编写clear方法
protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取购物车对象 Cart cart = (Cart) req.getSession().getAttribute("cart"); if (cart != null) { // 清空购物车 cart.clear(); // 重定向回原来的页面 resp.sendRedirect(req.getHeader("Referer")); } }
修改提交地址
<span class="cart_span"><a id="clearCart" href="cartServlet?action=clear">清空购物车</a></span>
确认清空购物车的提示
$("#clearCart").click(function () { return confirm("确定要清空购物车吗?"); });
编写update方法
protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取请求的商品id、数量 int count = WebUtils.parseInt(req.getParameter("count"), 1); int id = WebUtils.parseInt(req.getParameter("id"), 0); Cart cart = (Cart) req.getSession().getAttribute("cart"); if(cart != null){ cart.updateCount(id,count); // 重定向回原来的页面 resp.sendRedirect(req.getHeader("Referer")); } }
修改提交的表单
<td><input type="text" value="${entry.value.count}" style="width: 80px" class="updateCount" bookId="${entry.value.id}"></td>
确认修改数量的提示
$(".updateCount").change(function () { var name = $(this).parent().parent().find("td:first").text();//获取商品名称 var id = $(this).attr("bookId");//获取商品id var count = this.value;//获取商品数量 if(confirm("确定要修改【" + name + "】的数量为:" + count +"吗?")) { // 确认修改,发起请求 location = "${basePath}cartServlet?action=update&count=" + count + "&id=" + id; }else { // 取消修改 this.value = this.defaultValue; } });
在添加商品功能中保存商品名称
System.out.println("Referer:" + req.getHeader("Referer")); req.getSession().setAttribute("lastName",cartItem.getName()); resp.sendRedirect(req.getHeader("Referer"));
在首页修改数据的显示
<div style="text-align: center"> <c:if test="${empty sessionScope.cart.items}"> <span></span> <div> <span style="color: red">当前购物车为空</span> </div> </c:if> <c:if test="${not empty sessionScope.cart.items}"> <span>您的购物车中有${sessionScope.cart.totalCount}件商品</span> <div> 您刚刚将<span style="color: red">${sessionScope.lastName}</span>加入到了购物车中 </div> </c:if> </div>
注:本文章所含内容来源于尚硅谷教育,仅供学习参考使用。