项目四阶段搭建
- 项目搭建
- v3 -> v4
保持登录状态
- 需求
- 登录成功之后,在login_success.html、index.html页面,显示用户信息。
- 分析
- ServeltRequest:登录成功之后,使用的是重定向,而重定向是新的请求
- ServletContext : 登录成功之后,所有人都可以拿到你的个人的用户信息
- Cookie:登录成功之后,将个人信息存储到浏览器的缓存文件,存在一定的安全问题
- Session:登录成功之后,将个人信息存储到服务器
- 代码实现
public void login(HttpServletRequest request, HttpServletResponse response) {
//处理请求
String username = request.getParameter("username");
String password = request.getParameter("password");
UserService userService = new UserServiceImpl();
try {
User user = userService.login(username, password);
//调度页面
if (null != user) {
//登录成功 ,将用户信息存储到session, 跳转到login_success.html (重定向)
request.getSession().setAttribute("existUser", user);
response.sendRedirect(request.getContextPath() + "/user?method=toLoginSuccessPage");
} else {
//登录失败 , 跳转回login.html (请求转发)
String errorMsg = "账户或密码错误!";
request.setAttribute("errorMsg", errorMsg);
toLoginPage(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//index.html
<!-- 登录前风格-->
<div class="topbar-right" th:if="${null == session.existUser}">
<a th:href="@{/user(method=toLoginPage)}" class="login">登录</a>
<a th:href="@{/user(method=toRegistPage)}" class="register">注册</a>
<a
href="pages/cart/cart.html"
class="cart iconfont icon-gouwuche">
购物车
<div class="cart-num">3</div>
</a>
<a th:href="@{/manager.html}" class="admin">后台管理</a>
</div>
<!-- 登录后风格-->
<div class="topbar-right" th:if="${null != session.existUser}">
<span>欢迎你<b th:text="${session.existUser.userName}">张总</b></span>
<a href="#" class="register">注销</a>
<a
href="pages/cart/cart.jsp"
class="cart iconfont icon-gouwuche
">
购物车
<div class="cart-num">3</div>
</a>
<a href="pages/manager/book_manager.html" class="admin">后台管理</a>
</div>
注销登录功能
- 需求
- 在index.html、login_success.html页面,点击注销按钮,完成注销功能,回到index.html
- 代码实现
/**
* 注销登录功能
* @param request
* @param response
*/
public void logout(HttpServletRequest request,HttpServletResponse response){
//将保存在session的用户信息移除
request.getSession().removeAttribute(BookstoreConstant.SESSION_KEY_USER);
//移除成功之后
try {
response.sendRedirect(request.getContextPath() + "/index.html");
} catch (IOException e) {
e.printStackTrace();
}
}
<a th:href="@{/user(method=logout)}">注销</a>
图片验证码Kaptcha
- 概述
- 通过让用户填写验证码并在服务器端检查,防止浏览器端使用程序恶意访问。
- 开发步骤
- ①引入Kaptcha的相关jar包
- ②配置一个KaptchaServlet
- 用于生成一个图片验证码 , 该图片验证码的内容存储到了Session中(KAPTCHA_SESSION_KEY)
- ③测试匹配图片验证码
- ①引入Kaptcha的相关jar包
- ②配置一个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</url-pattern>
</servlet-mapping>
③测试匹配图片验证码
@WebServlet("/demo01")
public class Demo01Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取用户输入的验证码
String inputCode = req.getParameter("code");
//获取图片验证码的内容
Object existCode = req.getSession().getAttribute("KAPTCHA_SESSION_KEY");
//两个验证码匹配
System.out.println(inputCode.equals(existCode) ? "验证码正确!" :"验证码错误!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Kaptcha相关配置
- 代码实现
<!--图片验证码-->
<servlet>
<servlet-name>KaptchaServlet</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<!--设置边框-->
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>yes</param-value>
</init-param>
<!--设置边框颜色-->
<init-param>
<param-name>kaptcha.border.color</param-name>
<param-value>red</param-value>
</init-param>
<!--设置边框粗细-->
<init-param>
<param-name>kaptcha.border.thickness</param-name>
<param-value>10</param-value>
</init-param>
<!--设置内容-->
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>0123456789</param-value>
</init-param>
<!--设置验证码长度-->
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<!--设置字体样式-->
<init-param>
<param-name>kaptcha.textproducer.font.names</param-name>
<param-value>楷体</param-value>
</init-param>
<!--设置字体大小-->
<init-param>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>45</param-value>
</init-param>
<!--设置字体颜色-->
<init-param>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>green</param-value>
</init-param>
<!--设置字符间距-->
<init-param>
<param-name>kaptcha.textproducer.char.space</param-name>
<param-value>5</param-value>
</init-param>
<!--设置干扰线-->
<init-param>
<param-name>kaptcha.noise.impl</param-name>
<param-value>com.google.code.kaptcha.impl.DefaultNoise</param-value>
</init-param>
<!--设置干扰线颜色-->
<init-param>
<param-name>kaptcha.noise.color</param-name>
<param-value>red</param-value>
</init-param>
<!--设置背景起始颜色-->
<init-param>
<param-name>kaptcha.background.clear.from</param-name>
<param-value>pink</param-value>
</init-param>
<!--设置背景结束颜色-->
<init-param>
<param-name>kaptcha.background.clear.to</param-name>
<param-value>red</param-value>
</init-param>
</servlet>
注册功能引入kaptcha
- 需求
- 在regist.html页面,引入kaptcha图片验证码
- 代码实现
//regist.html
<div class="form-item">
<div>
<label>验证码:</label>
<div class="verify">
<input type="text" placeholder="请输入验证码" @change="checkCode()" v-model="code" name="code"/>
<!--访问KaptchaServlet-->
<img th:src="@{/kaptcha}" alt="无法获取验证码!" style="margin-left: 10px;width: 150px;height: 50px"/>
</div>
</div>
<span class="errMess" v-text="codeErrorMsg">请输入正确的验证码</span>
</div>
public void regist(HttpServletRequest req, HttpServletResponse resp) {
//使用BeanUtils自动封装
User inputUser = new User();
try {
//校验图片验证码
//获取用户输入的图片验证码
String inputCode = req.getParameter("code");
//获取图片验证码的内容
Object existCode = req.getSession().getAttribute("KAPTCHA_SESSION_KEY");
if (!inputCode.equals(existCode)) {
//图片验证码校验失败
String codeErrorMsg = "验证码错误!";
req.setAttribute("codeErrorMsg", codeErrorMsg);
toRegistPage(req, resp);
return;
}
BeanUtils.populate(inputUser, req.getParameterMap());
System.out.println("inputUser = " + inputUser);
UserService userService = new UserServiceImpl();
//校验用户名是否存在
User dbUser = userService.selectUserByUsername(inputUser.getUserName());
if (null != dbUser) {
//注册失败,用户名已经存在 , 跳转回regist.html (转发)
resp.setContentType("text/html;charset=utf-8");
String errorMsg = "用户名已经存在!";
req.setAttribute("errorMsg", errorMsg);
toRegistPage(req, resp);
return;
}
int addUser = userService.addUser(inputUser);
if (addUser > 0) {
//添加成功 , 跳转到regist_success.html (重定向)
resp.sendRedirect(req.getContextPath() + "/user?method=toRegistSuccessPage");
} else {
//添加失败 , 跳转回regist.html (转发)
toLoginPage(req, resp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
刷新图片验证码(掌握)
- 需求
- 点击图片验证码并刷新
- 代码实现
<img id="codeImg" @click="refreshImg()" th:src="@{/kaptcha}" alt="无法获取验证码!" style="margin-left: 10px;width: 150px;height: 50px"/>
<script>
/**
* 刷新图片验证码
*/
refreshImg(){
var imgEle = document.getElementById("codeImg");
imgEle.setAttribute("src","kaptcha");
}
</script>
跳转到购物车
- 需求
- 在index.html页面,点击购物车按钮,跳转到cart.html页面。
- 代码实现
@WebServlet("/protected/cart")
public class ProtectedCartServlet extends ModelBaseServlet {
/**
* 转发到cart.html
*
* @param request
* @param response
*/
public void toCartPage(HttpServletRequest request, HttpServletResponse response) {
try {
processTemplate("pages/cart/cart", request, response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//index.html
<!-- 登录前风格-->
<div class="topbar-right" th:if="${null == session.existUser}">
<a th:href="@{/user(method=toLoginPage)}" class="login">登录</a>
<a th:href="@{/user(method=toRegistPage)}" class="register">注册</a>
<a
th:href="@{/protected/cart(method=toCartPage)}"
class="cart iconfont icon-gouwuche">
购物车
<div class="cart-num">3</div>
</a>
<a th:href="@{/manager.html}" class="admin">后台管理</a>
</div>
<!-- 登录后风格-->
<div class="topbar-right" th:if="${null != session.existUser}">
<span>欢迎你<b th:text="${session.existUser.userName}">张总</b></span>
<a th:href="@{/user(method=logout)}" class="register">注销</a>
<a
th:href="@{/protected/cart(method=toCartPage)}"
class="cart iconfont icon-gouwuche">
购物车
<div class="cart-num">3</div>
</a>
<a href="pages/manager/book_manager.html" class="admin">后台管理</a>
</div>
购物车模型之CartItem
- 成员变量
- bookId : 图书编号
- imgPath :图书图片
- bookName : 图书名称
- count : 图书数量
- price : 图书价格
- amount : 小计
- amount = count * price
- 成员方法
- countIncrease() : 购物车项数量加一
- countDecrease() : 购物车项数量减一
- 代码实现
/**
* 购物车模型之购物车项
*/
public class CartItem {
private Integer bookId;//图书编号
private String imgPath;//图书图片
private String bookName;//图书名称
private Integer count;//图书数量
private Double price;//图书价格
private Double amount;//小计
public CartItem() {
}
public CartItem(Integer bookId, String imgPath, String bookName, Integer count, Double price, Double amount) {
this.bookId = bookId;
this.imgPath = imgPath;
this.bookName = bookName;
this.count = count;
this.price = price;
this.amount = amount;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Double getAmount() {
return this.count * this.price;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public void countIncrease(){
this.count++;
}
public void countDecrease() {
this.count--;
}
@Override
public String toString() {
return "CartItem{" +
"bookId=" + bookId +
", imgPath='" + imgPath + '\'' +
", bookName='" + bookName + '\'' +
", count=" + count +
", price=" + price +
", amount=" + amount +
'}';
}
}
购物车模型之Cart
- 成员变量
- 商品总数量
- 商品总金额
- 购物车项列表
- 成员方法
- 获取商品总数量
- 获取商品总金额
- 获取购物车项列表
- 指定购物车项数量减一
- 指定购物车项数量加一
- 修改指定购物车项数量
- 删除指定购物车项
- 将图书添加到购物车
- 代码实现
/**
* 购物车模型之Cart
*/
public class Cart {
private Integer totalCount;//商品总数量
private Double totalAmount;//商品总金额(总计)
private Map<Integer,CartItem> cartItemMap = new HashMap<>(); //购物车项列表
/**
* 获取商品总数量 = 购物车项数量相加
* @return
*/
public Integer getTotalCount() {
Collection<CartItem> cartItems = cartItemMap.values();
Integer totalCount = 0 ;
for (CartItem cartItem : cartItems) {
totalCount = totalCount + cartItem.getCount();
}
this.totalCount = totalCount;
return this.totalCount;
}
/**
* 获取商品总金额 = 购物车项小计相加
* @return
*/
public Double getTotalAmount() {
Collection<CartItem> cartItems = cartItemMap.values();
Double totalAmount = 0.0;
for (CartItem cartItem : cartItems) {
Double amount = cartItem.getAmount();
totalAmount = totalAmount + amount;
}
this.totalAmount = totalAmount;
return this.totalAmount;
}
/**
* 获取购物车项列表
* @return
*/
public Map<Integer, CartItem> getCartItemMap() {
return cartItemMap;
}
/**
* 指定购物车项数量减一
* @param bookId
*/
public void cartItemCountDecrease(Integer bookId){
CartItem cartItem = cartItemMap.get(bookId);
cartItem.countDecrease();
}
/**
* 指定购物车项数量加一
* @param bookId
*/
public void cartItemCountIncrease(Integer bookId){
CartItem cartItem = cartItemMap.get(bookId);
cartItem.countIncrease();
}
/**
* 修改指定购物车项的数量
* @param bookId
* @param newCount : 新数量
*/
public void updateCartItemCount(Integer bookId , Integer newCount){
CartItem cartItem = cartItemMap.get(bookId);
cartItem.setCount(newCount);
}
/**
* 删除指定购物车项
* @param bookId
*/
public void removeCartItem(Integer bookId){
cartItemMap.remove(bookId);
}
/**
* 将图书添加到购物车
* @param book
*/
public void addBook2Cart(Book book){
//判断购物车是否包含该图书
Integer bookId = book.getBookId();
if (cartItemMap.containsKey(bookId)) {
//包含该图书,在原来的购物车项数量加一
cartItemCountIncrease(bookId);
} else {
//不包含该图书,创建新的购物车项
CartItem cartItem = new CartItem(
bookId,
book.getImgPath(),
book.getBookName(),
1,
book.getPrice(),
1 * book.getPrice()
);
cartItemMap.put(bookId,cartItem);
}
}
}
public class Demo01 {
public static void main(String[] args) {
Book book1 = new Book(
1,
"java",
"oldqiu",
100.0,
1000,
10000,
"girl.jpg"
);
Book book2 = new Book(
2,
"javase",
"搞死你",
100.0,
10000,
100000,
"girl2.jpg"
);
Book book3 = new Book(
3,
"linux",
"linux",
100.0,
20000,
200000,
"girl3.jpg"
);
Cart cart = new Cart();
cart.addBook2Cart(book1);
cart.addBook2Cart(book1);
cart.addBook2Cart(book1);
cart.addBook2Cart(book1);
cart.addBook2Cart(book2);
cart.addBook2Cart(book3);
System.out.println("总数量 : " + cart.getTotalCount());
System.out.println("总金额 : " + cart.getTotalAmount());
System.out.println("购物车项列表 : " + cart.getCartItemMap());
}
}
添加商品进购物车
- 需求
- 在index.html,点击加入购物车按钮,加入购物车成功后,跳转到index.html,显示商品总 数量
- 代码实现
//index.html
<a th:href="@{/protected/cart(method=addBook2Cart,bookId=${book.bookId})}">
加入购物车
</a>
@WebServlet("/protected/cart")
public class ProtectedCartServlet extends ModelBaseServlet {
/**
* 将图书添加到购物车
*
* @param request
* @param response
*/
public void addBook2Cart(HttpServletRequest request, HttpServletResponse response) {
try {
Integer bookId = Integer.parseInt(request.getParameter("bookId"));
System.out.println("bookId = " + bookId);
BookService bookService = new BookServiceImpl();
Book book = bookService.selectBookById(bookId);
//判断之前有没有购物车
Cart cart = (Cart) request.getSession().getAttribute(BookstoreConstant.SESSION_KEY_CART);
if (null == cart) {
//之前没有购物车
cart = new Cart();
} else {
//之前有购物车
}
cart.addBook2Cart(book);
request.getSession().setAttribute(BookstoreConstant.SESSION_KEY_CART, cart);
//购物车添加完成 , 跳转到index.html (重定向)
response.sendRedirect(request.getContextPath() + "/index.html");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//index.html
<!-- 登录前风格-->
<div class="topbar-right" th:if="${null == session.existUser}">
<a th:href="@{/user(method=toLoginPage)}" class="login">登录</a>
<a th:href="@{/user(method=toRegistPage)}" class="register">注册</a>
<a
th:href="@{/protected/cart(method=toCartPage)}"
class="cart iconfont icon-gouwuche">
购物车
<div class="cart-num"
th:if="${session.existCart==null||session.existCart.totalCount==0}">
0
</div>
<div class="cart-num"
th:unless="${session.existCart==null||session.existCart.totalCount==0}"
th:text="${session.existCart.totalCount}">
0
</div>
</a>
<a th:href="@{/manager.html}" class="admin">后台管理</a>
</div>
<!-- 登录后风格-->
<div class="topbar-right" th:if="${null != session.existUser}">
<span>欢迎你<b th:text="${session.existUser.userName}">张总</b></span>
<a th:href="@{/user(method=logout)}" class="register">注销</a>
<a
th:href="@{/protected/cart(method=toCartPage)}"
class="cart iconfont icon-gouwuche">
购物车
<div class="cart-num"
th:if="${session.existCart==null||session.existCart.totalCount==0}">
0
</div>
<div class="cart-num"
th:unless="${session.existCart==null||session.existCart.totalCount==0}"
th:text="${session.existCart.totalCount}">
0
</div>
</a>
<a href="pages/manager/book_manager.html" class="admin">后台管理</a>
</div>
显示购物车列表
- 需求
- 在index.html,点击购物车按钮,跳转到cart.html,并展示购物车列表。
- 代码实现
@WebServlet("/protected/cart")
public class ProtectedCartServlet extends ModelBaseServlet {
/**
* 转发到cart.html
*
* @param request
* @param response
*/
public void toCartPage(HttpServletRequest request, HttpServletResponse response) {
try {
//获取购物车信息
//Object existCart = request.getSession().getAttribute(BookstoreConstant.SESSION_KEY_CART);
processTemplate("pages/cart/cart", request, response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//cart.html
<div class="w">
<!--购物车项列表-->
<table>
<thead>
<tr>
<th>图片</th>
<th>商品名称</th>
<th>数量</th>
<th>单价</th>
<th>金额</th>
<th>操作</th>
</tr>
</thead>
<!-- 购物车为空时 -->
<tbody th:if="${session.existCart==null||session.existCart.totalCount==0}">
<tr>
<td colspan="6">
<a href="index.html">购物车空空如也,请抓紧购物吧!!!!</a>
</td>
</tr>
</tbody>
<!-- 购物车不为空时 -->
<tbody th:unless="${session.existCart==null||session.existCart.totalCount==0}">
<!--cartItemEntry : 键值对对象(键:bookId, 值:CartItem对象)-->
<tr th:each="cartItemEntry : ${session.existCart.cartItemMap}">
<td>
<img th:src="${cartItemEntry.value.imgPath}" alt=""/>
</td>
<td th:text="${cartItemEntry.value.bookName}">活着</td>
<td>
<span class="count">-</span>
<input class="count-num" type="text" th:value="${cartItemEntry.value.count}"/>
<span class="count">+</span>
</td>
<td th:text="${cartItemEntry.value.price}">36.8</td>
<td th:text="${cartItemEntry.value.amount}">36.8</td>
<td><a href="">删除</a></td>
</tr>
</tbody>
</table>
<!--展示商品总数量、总金额-->
<div class="footer">
<div class="footer-left">
<a href="#" class="clear-cart">清空购物车</a>
<a href="#">继续购物</a>
</div>
<!--购物车为空-->
<div class="footer-right" th:if="${session.existCart==null||session.existCart.totalCount==0}">
<div>共<span>0</span>件商品</div>
<div class="total-price">总金额<span>0.0</span>元</div>
<a class="pay" href="checkout.html">去结账</a>
</div>
<!--购物车不为空-->
<div class="footer-right" th:unless="${session.existCart==null||session.existCart.totalCount==0}">
<div>共<span th:text="${session.existCart.totalCount}">3</span>件商品</div>
<div class="total-price">总金额<span th:text="${session.existCart.totalAmount}">99.9</span>元</div>
<a class="pay" href="checkout.html">去结账</a>
</div>
</div>
</div>
清空购物车
- 需求
- 在cart.html中,点击清空购物车按钮,将Session域中的Cart对象移除,从而实现清空购物 车功能。
- 代码实现
<a th:href="@{/protected/cart(method=clearCart)}" class="clear-cart">清空购物车</a>
public void clearCart(HttpServletRequest request, HttpServletResponse response){
request.getSession().removeAttribute(BookstoreConstant.SESSION_KEY_CART);
//清空购物车完成,跳转到cart.html(重定向)
try {
//response.sendRedirect("/bookstore/protected/cart?method=toCartPage");
System.out.println(request.getContextPath() + File.separator
+ request.getServletPath() + "?method=toCartPage");
response.sendRedirect(request.getContextPath()
+ request.getServletPath() + "?method=toCartPage");
} catch (IOException e) {
e.printStackTrace();
}
}
购物车项减一
- 需求
- 在cart.html中,点击减号按钮,如果当前购物车项数量为1时删除;如果当前购物车项数量大 于1时减一。
- 代码实现
<a th:href="@{/protected/cart(method=cartItemCountDecrease,bookId=${cartItemEntry.key})}">
-
</a>
/**
* 指定购物车项数量减一
* @param request
* @param response
*/
public void cartItemCountDecrease(HttpServletRequest request, HttpServletResponse response){
Integer bookId = Integer.parseInt(request.getParameter("bookId"));
//获取指定bookId的购物车项数量
Cart cart = (Cart) request.getSession().getAttribute(BookstoreConstant.SESSION_KEY_CART);
CartItem cartItem = cart.getCartItemMap().get(bookId);
if (cartItem.getCount() <= 1) {
//直接移除购物车项
cart.removeCartItem(bookId);
} else {
//购物车项数量减一
cart.cartItemCountDecrease(bookId);
}
//
try {
response.sendRedirect(request.getContextPath()
+ request.getServletPath() + "?method=toCartPage");
} catch (IOException e) {
e.printStackTrace();
}
}
购物车项加一
- 需求
- 在cart.html中,点击加号按钮,在原有商品数量基础上加1
- 代码实现
<a th:href="@{/protected/cart(method=cartItemCountIncrease,bookId=${cartItemEntry.key})}">
+
</a>
/**
* 指定购物车项数量加一
* @param request
* @param response
*/
public void cartItemCountIncrease(HttpServletRequest request, HttpServletResponse response){
Integer bookId = Integer.parseInt(request.getParameter("bookId"));
//获取指定bookId的购物车项数量
Cart cart = (Cart) request.getSession().getAttribute(BookstoreConstant.SESSION_KEY_CART);
cart.cartItemCountIncrease(bookId);
//
try {
response.sendRedirect(request.getContextPath()
+ request.getServletPath() + "?method=toCartPage");
} catch (IOException e) {
e.printStackTrace();
}
}
删除购物车项
- 需求
- 在cart.html中,点击删除按钮,删除指定购物车项
- 代码实现
<a th:href="@{/protected/cart(method=removeCartItem,bookId=${cartItemEntry.key})}">
删除
</a>
public void removeCartItem(HttpServletRequest request, HttpServletResponse response){
Integer bookId = Integer.parseInt(request.getParameter("bookId"));
//获取指定bookId的购物车项数量
Cart cart = (Cart) request.getSession().getAttribute(BookstoreConstant.SESSION_KEY_CART);
cart.removeCartItem(bookId);
//
try {
response.sendRedirect(request.getContextPath()
+ request.getServletPath() + "?method=toCartPage");
} catch (IOException e) {
e.printStackTrace();
}
}
修改购物车项数量
- 需求
- 在cart.html中,用户在文本框输入新数据后,根据用户输入修改购物车项数量
- 代码实现
<input class="count-num" type="text" th:value="${cartItemEntry.value.count}"
@change="updateCartItemCount()"/>
<!--隐藏的input,value为bookId-->
<input type="hidden" th:value="${cartItemEntry.key}">
<script>
var vue = new Vue({
el: "#app",
data: {},
methods: {
updateCartItemCount() {
//console.log(bookId);//?
var bookId = event.target.nextElementSibling.value;
var newCount = event.target.value;
console.log("newCount : " + newCount);
if (newCount <= 0) {
location.href = "protected/cart?method=removeCartItem&bookId=" + bookId;
} else {
//请求ProtectedCartServlet中的updateCartItemCount方法, 并传递bookId、newCount两个参数
location.href = "protected/cart?method=updateCartItemCount&bookId=" + bookId + "&newCount=" + newCount;
}
}
}
})
</script>
/**
* 修改购物车项数量
* @param request
* @param response
*/
public void updateCartItemCount(HttpServletRequest request, HttpServletResponse response) {
Integer bookId = Integer.parseInt(request.getParameter("bookId"));
Integer newCount = Integer.parseInt(request.getParameter("newCount"));
Cart cart = (Cart) request.getSession().getAttribute(BookstoreConstant.SESSION_KEY_CART);
if (newCount <= 0) {
//直接删除购物车项
cart.removeCartItem(bookId);
} else {
//修改购物车项数量
cart.updateCartItemCount(bookId, newCount);
}
try {
response.sendRedirect(request.getContextPath()
+ request.getServletPath() + "?method=toCartPage");
} catch (IOException e) {
e.printStackTrace();
}
}
BigDecimal精度调整
代码实现
public Double getAmount() {
BigDecimal countBig = new BigDecimal(this.count + "");
BigDecimal priceBig = new BigDecimal(this.price + "");
this.amount = countBig.multiply(priceBig).doubleValue();
return this.amount ;
}
public Double getTotalAmount() {
Collection<CartItem> cartItems = cartItemMap.values();
BigDecimal totalAmountBig = new BigDecimal(0.0 + "");
for (CartItem cartItem : cartItems) {
BigDecimal amountBig = new BigDecimal(cartItem.getAmount() + "");
totalAmountBig = totalAmountBig.add(amountBig);
}
this.totalAmount = totalAmountBig.doubleValue();
return this.totalAmount;
}