概念
通过以上多篇文章的讲解,对该项目的功能已经实现了很多,本文将对该项目的用户注册,登录,修改用户信息,以及用户添加至购物车的商品进行提交订单等功能的实现。
注册功能实现
点击head.jsp头部页面的注册按钮,触发超链接跳转至user_register.jsp页面,其页面代码如下
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<title>用户注册</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/simpleCart.min.js"></script>
</head>
<body>
<jsp:include page="/header.jsp">
<jsp:param name="flag" value="10"></jsp:param>
</jsp:include>
<div class="account">
<div class="container">
<div class="register">
<c:if test="${!empty msg }">
<div class="alert alert-danger">${msg }</div>
</c:if>
<form action="/user_rigister" method="post">
<div class="register-top-grid">
<h3>注册新用户</h3>
<div class="input">
<span>用户名 <label style="color:red;">*</label></span>
<input type="text" name="username" placeholder="请输入用户名" required="required">
</div>
<div class="input">
<span>邮箱 <label style="color:red;">*</label></span>
<input type="text" name="email" placeholder="请输入邮箱" required="required">
</div>
<div class="input">
<span>密码 <label style="color:red;">*</label></span>
<input type="password" name="password" placeholder="请输入密码" required="required">
</div>
<div class="input">
<span>收货人<label></label></span>
<input type="text" name="name" placeholder="请输入收货">
</div>
<div class="input">
<span>收货电话<label></label></span>
<input type="text" name="phone" placeholder="请输入收货电话">
</div>
<div class="input">
<span>收货地址<label></label></span>
<input type="text" name="address" placeholder="请输入收货地址">
</div>
<div class="clearfix"> </div>
</div>
<div class="register-but text-center">
<input type="submit" value="提交">
<div class="clearfix"> </div>
</div>
</form>
<div class="clearfix"> </div>
</div>
</div>
</div>
<jsp:include page="/footer.jsp"></jsp:include>
</body>
</html>
用户填写完注册信息后,点击提交按钮,将所有数据以表单的形式提交给服务器,因此需要在servlet包中创建UserRegisterServlet类,用于接收用户的注册信息数据,并实现注册功能。
package servlet;
import model.User;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;
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;
import java.lang.reflect.InvocationTargetException;
@WebServlet(name = "user_register",urlPatterns = "/user_rigister")
public class UserRegisterServlet extends HttpServlet {
private UserService uService = new UserService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user = new User();
try {
BeanUtils.copyProperties(user, request.getParameterMap());
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(uService.register(user)) {
request.setAttribute("msg", "注册成功,请登录!");
request.getRequestDispatcher("user_login.jsp").forward(request, response);
}else {
request.setAttribute("msg", "用户名或邮箱重复,请重新填写!");
request.getRequestDispatcher("user_register.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
以上代码中,使用request对象的getParameterMap方法将用户提交的数据以map集合的形式接收,并通过c3p0插件的BeanUtils工具类将map集合的数据转换成User实体类的数据,并将User对象传递给UserService类进行验证用户名或者邮箱是否重复,如果无误则执行注册操作。因此,需要在servie包中创建UserService类
package service;
import dao.UserDao;
import model.Page;
import model.User;
import java.sql.SQLException;
import java.util.List;
public class UserService {
private UserDao uDao = new UserDao();
public boolean register(User user) {
try {
if(uDao.isUsernameExist(user.getUsername())) {
return false;
}
if(uDao.isEmailExist(user.getEmail())) {
return false;
}
uDao.addUser(user);
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
以上代码中,定义了注册的方法,并在注册之前分两步验证用户注册的用户名和邮箱是否已存在,这里需要将用户的注册信息发送给dao数据访问层进行sql操作,在dao包中创建UserDao类,并定义对应的方法
package dao;
import model.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.DataSourceUtils;
import java.sql.SQLException;
import java.util.List;
public class UserDao {
public void addUser(User user) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "insert into user(username,email,password,name,phone,address,isadmin,isvalidate) values(?,?,?,?,?,?,?,?)";
r.update(sql,user.getUsername(),user.getEmail(),user.getPassword(),user.getName(),user.getPhone(),user.getAddress(),user.isIsadmin(),user.isIsvalidate());
}
public boolean isUsernameExist(String username) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where username = ?";
User u = r.query(sql, new BeanHandler<User>(User.class),username);
if(u==null) {
return false;
}else {
return true;
}
}
public boolean isEmailExist(String email) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where email = ?";
User u = r.query(sql, new BeanHandler<User>(User.class),email);
if(u==null) {
return false;
}else {
return true;
}
}
}
最后servlet会将注册成功的信息返回给浏览器,并跳转至user_login.jsp登录页面,否则返回注册页面,要求用户重新注册。其登录页面代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<title>用户登录</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/simpleCart.min.js"></script>
</head>
<body>
<!--header-->
<jsp:include page="header.jsp">
<jsp:param name="flag" value="9"></jsp:param>
</jsp:include>
<!--//header-->
<!--account-->
<div class="account">
<div class="container">
<div class="register">
<c:if test="${!empty msg }">
<div class="alert alert-success">${msg }</div>
</c:if>
<c:if test="${!empty failMsg }">
<div class="alert alert-danger">${failMsg }</div>
</c:if>
<form action="/user_login" method="post">
<div class="register-top-grid">
<h3>用户登录</h3>
<div class="input">
<span>用户名/邮箱 <label style="color:red;">*</label></span>
<input type="text" name="ue" placeholder="请输入用户名" required="required">
</div>
<div class="input">
<span>密码 <label style="color:red;">*</label></span>
<input type="password" name="password" placeholder="请输入密码" required="required">
</div>
<div class="clearfix"> </div>
</div>
<div class="register-but text-center">
<input type="submit" value="提交">
<div class="clearfix"> </div>
</div>
</form>
<div class="clearfix"> </div>
</div>
</div>
</div>
<!--//account-->
<!--footer-->
<jsp:include page="footer.jsp"></jsp:include>
<!--//footer-->
</body>
</html>
登录功能实现
用户可以在注册成功后,自动进入登录页面,也可以通过点击头部页面的登录超链接进入登录页面,在登录页面输入用户的用户名和密码,点击提交按钮,将用户名,密码以表单的形式提交给服务器进行验证用户的真实性。
因此需要在servlet包中创建UserLoginServlet类,接收用户的登录请求以及数据参数进行验证
package servlet;
import model.User;
import service.UserService;
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(name = "user_login",urlPatterns = "/user_login")
public class UserLoginServlet extends HttpServlet {
private UserService uService = new UserService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String ue = request.getParameter("ue");
String password = request.getParameter("password");
User user = uService.login(ue, password);
if(user==null) {
request.setAttribute("failMsg", "用户名、邮箱或者密码错误,请重新登录!");
request.getRequestDispatcher("/user_login.jsp").forward(request, response);
}else {
request.getSession().setAttribute("user", user);
request.getRequestDispatcher("/user_center.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
以上代码中,接收用户的登录信息后,传递给业务逻辑层进行执行,并接收返回的user对象,如果user为空,说明用户的登录信息有误,要求其重新登录,user不为空则说明当前用户登录成功,则进入用户信息页面。
因此这里需要在UserService类中定义登录的方法
public User login(String ue,String password) {
User user=null;
try {
user = uDao.selectByUsernamePassword(ue, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(user!=null) {
return user;
}
try {
user=uDao.selectByEmailPassword(ue, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(user!=null) {
return user;
}
return null;
}
以上代码中,验证了用户登录的两种方式,用户可能使用的是用户名登录或者邮箱地址登录,因此dao层中需要使用两种方式来进行查询。在UserDao类中定义两个方法来执行sql操作
public User selectByUsernamePassword(String username,String password) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where username=? and password=?";
return r.query(sql, new BeanHandler<User>(User.class),username,password);
}
public User selectByEmailPassword(String email,String password) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where email=? and password=?";
return r.query(sql, new BeanHandler<User>(User.class),email,password);
}
最后,验证通过则登录成功,跳转至用户信息页面显示用户个人信息
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>个人中心</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/simpleCart.min.js"></script>
</head>
<body>
<jsp:include page="/header.jsp">
<jsp:param value="4" name="flag"/>
</jsp:include>
<c:if test="${empty user}"><%response.sendRedirect("/index");%></c:if>
<!--account-->
<div class="account">
<div class="container">
<div class="register">
<c:if test="${!empty msg }">
<div class="alert alert-success">${msg }</div>
</c:if>
<c:if test="${!empty failMsg }">
<div class="alert alert-danger">${failMsg }</div>
</c:if>
<div class="register-top-grid">
<h3>个人中心</h3>
<form action="/user_changeaddress" method="post">
<!-- 收货信息 start -->
<h4>收货信息</h4>
<div class="input">
<span>收货人<label></label></span>
<input type="text" name="name" value="${user.name }" placeholder="请输入收货">
</div>
<div class="input">
<span>收货电话</span>
<input type="text" name="phone" value="${user.phone }" placeholder="请输入收货电话">
</div>
<div class="input">
<span>收货地址</span>
<input type="text" name="address" value="${user.address }" placeholder="请输入收货地址">
</div>
<div class="register-but text-center">
<input type="submit" value="提交">
</div>
<!-- 收货信息 end -->
</form>
<hr>
<form action="/user_changepwd" method="post">
<h4>安全信息</h4>
<div class="input">
<span>原密码</span>
<input type="text" name="password" placeholder="请输入原密码">
</div>
<div class="input">
<span>新密码</span>
<input type="text" name="newPassword" placeholder="请输入新密码">
</div>
<div class="clearfix"> </div>
<div class="register-but text-center">
<input type="submit" value="提交">
</div>
</form>
</div>
<div class="clearfix"> </div>
</div>
</div>
</div>
<jsp:include page="/footer.jsp"></jsp:include>
</body>
</html>
登录成功后,头部信息中显示“我的订单”,“个人中心”以及“退出”等超链接选项功能
以上界面中,用户可以对个人信息进行更改,包括修改密码等等功能。
更改收件人信息
当用户登录成功后,更改收件人信息,也就是上图中的第一个表单,点击提交后,将修改的信息发送给服务器,服务器将更新后的数据进行同步至数据库中。
因此需要在servlet包中创建UserChangeAddressServlet类完成对应操作。
package servlet;
import model.User;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;
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;
import java.lang.reflect.InvocationTargetException;
@WebServlet(name = "user_changeaddress",urlPatterns = "/user_changeaddress")
public class UserChangeAddressServlet extends HttpServlet {
private UserService uService = new UserService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User loginUser = (User) request.getSession().getAttribute("user");
try {
BeanUtils.copyProperties(loginUser, request.getParameterMap());
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uService.updateUserAddress(loginUser);
request.setAttribute("msg", "收件信息更新成功!");
request.getRequestDispatcher("/user_center.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
以上代码中,将用户修改的个人信息通过BeanUtil工具类同步到session中,并将更新后的数据传递给UserService,因此需要在UserService类中定义更新个人信息的方法
public void updateUserAddress(User user) {
try {
uDao.updateUserAddress(user);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
接着,该方法将更新的数据发送给dao层执行
public void updateUserAddress(User user) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql ="update user set name = ?,phone=?,address=? where id = ?";
r.update(sql,user.getName(),user.getPhone(),user.getAddress(),user.getId());
}
最后,更新成功后,返回个人中心页面,并同步刷新页面。
更改登录密码
在个人中心页面的第二个表单中,用户可以更改登录密码,通过输入原密码,以及新密码的方式提交给服务器进行操作。
因此需要在servlet中创建UserChangePwd类执行用户的操作
package servlet;
import model.User;
import service.UserService;
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(name = "user_changepwd",urlPatterns = "/user_changepwd")
public class UserChangePwd extends HttpServlet {
private UserService uService = new UserService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String password = request.getParameter("password");
String newPwd = request.getParameter("newPassword");
User u = (User) request.getSession().getAttribute("user");
if(password.equals(u.getPassword())) {
u.setPassword(newPwd);
uService.updatePwd(u);
request.setAttribute("msg", "修改成功!");
request.getRequestDispatcher("/user_center.jsp").forward(request, response);
}else {
request.setAttribute("failMsg", "修改失败,原密码不正确,你再想想!");
request.getRequestDispatcher("/user_center.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
以上代码中,获得用户修改密码的数据请求后,将原密码数据与session中保存的用户信息进行核对,如果原密码正确,则将新密码发送给UserService进行执行,因此需要在UserService中定义方法
public void updatePwd(User user) {
try {
uDao.updatePwd(user);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
接着在UserDao中定义对应的方法执行修改的sql操作
public void updatePwd(User user) throws SQLException {
QueryRunner r = new QueryRunner(DataSourceUtils.getDataSource());
String sql ="update user set password = ? where id = ?";
r.update(sql,user.getPassword(),user.getId());
}
最后,修改成功后返回个人中心页面,如果原密码错误,也返回个人中心页面,并提示用户密码错误,重新提交正确的原密码才能修改密码。
提交订单
用户登录成功后,用户可以进行提交订单操作,需要先将商品添加至购物车,接着通过购物车中提交订单。加入购物车的功能前面文章中已经讲解并实现,这里不再赘述,我们进行购物车页面,点击提交订单
点击提交订单后,将用户的商品信息发送给服务器,因此需要在servlet包中创建OrderSubmitServlet类
package servlet;
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(name = "order_submit",urlPatterns = "/order_submit")
public class OrderSubmitServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getSession().getAttribute("user")!=null) {
request.getRequestDispatcher("/order_submit.jsp").forward(request, response);
}else {
request.setAttribute("failMsg", "请登录后,再提交订单!");
request.getRequestDispatcher("/user_login.jsp").forward(request, response);
}
}
}
以上代码中,接收用户的提交订单请求后,验证了当前用户是否处于登录状态,如果没有登录,则直接跳转至登录页面进行登录,登录后跳转至order_submit.jsp支付界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>支付</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="layer/layer.js"></script>
<script type="text/javascript" src="js/cart.js"></script>
</head>
<body>
<jsp:include page="header.jsp"></jsp:include>
<div class="cart-items">
<div class="container">
<h2>确认收货信息</h2>
<form class="form-horizontal" action="/order_confirm" method="post" id="payform">
<div class="row">
<label class="control-label col-md-1">收货人</label>
<div class="col-md-6">
<input type="text" class="form-control" name="name" value="${user.name }" style="height:auto;padding:10px;" placeholder="输入收货人" required="required"><br>
</div>
</div>
<div class="row">
<label class="control-label col-md-1">收货电话</label>
<div class="col-md-6">
<input type="text" class="form-control" name="phone" value="${user.phone }" style="height:auto;padding:10px;" placeholder="输入收货电话" required="required"><br>
</div>
</div>
<div class="row">
<label class="control-label col-md-1">收货地址</label>
<div class="col-md-6">
<input type="text" class="form-control" name="address" value="${user.address }" style="height:auto;padding:10px;" placeholder="输入收货地址" required="required"><br>
</div>
</div>
<br><hr><br>
<h2>选择支付方式</h2>
<h3>支付金额: ${order.total }</h3><br><br>
<div class="col-sm-6 col-md-4 col-lg-3 " >
<label>
<div class="thumbnail">
<input type="radio" name="paytype" value="1" checked="checked" />
<img src="images/wechat.jpg" alt="微信支付">
</div>
</label>
</div>
<div class="col-sm-6 col-md-4 col-lg-3 " >
<label>
<div class="thumbnail">
<input type="radio" name="paytype" value="2" />
<img src="images/alipay.jpg" alt="支付宝支付">
</div>
</label>
</div>
<div class="clearfix"> </div>
<div class="register-but text-center">
<input type="submit" value="确认订单">
<div class="clearfix"> </div>
</div>
</form>
</div>
</div>
<!--footer-->
<jsp:include page="footer.jsp"></jsp:include>
<!--//footer-->
<script type="text/javascript">
function dopay(paytype){
$("#paytype").val(paytype);
$("#payform").submit();
}
</script>
</body>
</html>
用户可以在该界面进行确认收货信息,如果有错误可以进行直接修改收货人信息,并且选择支付方式,确认无误后,点击确定订单,将信息提交给服务器
因此需要在servlet中创建OrderConfirmServlet类
package servlet;
import model.Order;
import model.User;
import org.apache.commons.beanutils.BeanUtils;
import service.OrderService;
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;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
@WebServlet(name = "order_confirm",urlPatterns = "/order_confirm")
public class OrderConfirmServlet extends HttpServlet {
private OrderService oService = new OrderService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Order o = (Order) request.getSession().getAttribute("order");
try {
BeanUtils.copyProperties(o, request.getParameterMap());
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
o.setDatetime(new Date());
o.setStatus(2);
o.setUser((User) request.getSession().getAttribute("user"));
oService.addOrder(o);
request.getSession().removeAttribute("order");
request.setAttribute("msg", "订单支付成功!");
request.getRequestDispatcher("/order_success.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
以上代码中,接收到用户的确认订单请求和数据参数后,将数据同步至session中的order对象,并获得当前时间,更改支付状态,同步用户的收货信息,并把order对象传递给OrderService订单业务逻辑层,因此需要在service中创建OrderService类
package service;
import model.Order;
import model.OrderItem;
import model.Page;
import utils.DataSourceUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class OrderService {
private OrderDao oDao = new OrderDao();
public void addOrder(Order order) {
Connection con = null;
try {
con = DataSourceUtils.getConnection();
con.setAutoCommit(false);
oDao.insertOrder(con, order);
int id = oDao.getLastInsertId(con);
order.setId(id);
for(OrderItem item : order.getItemMap().values()) {
oDao.insertOrderItem(con, item);
}
con.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(con!=null)
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
以上代码中,确认当前服务器是否还与数据库保持持久化连接状态,并把订单信息以及连接对象发送给数据访问层执行提交订单操作,将添加成功后,获得返回的该订单的订单编号,并存储至order对象中。因此需要在Dao包中创建OrderDao类。
package dao;
import model.Order;
import model.OrderItem;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.DataSourceUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class OrderDao {
public void insertOrder(Connection con, Order order) throws SQLException {
QueryRunner r = new QueryRunner();
String sql = "insert into `order`(total,amount,status,paytype,name,phone,address,datetime,user_id) values(?,?,?,?,?,?,?,?,?)";
r.update(con,sql,
order.getTotal(),order.getAmount(),order.getStatus(),
order.getPaytype(),order.getName(),order.getPhone(),
order.getAddress(),order.getDatetime(),order.getUser().getId() );
}
public int getLastInsertId(Connection con) throws SQLException {
QueryRunner r = new QueryRunner();
String sql = "select last_insert_id()";
Long bi = r.query(con, sql,new ScalarHandler<Long>());
return Integer.parseInt(bi.toString());
}
public void insertOrderItem(Connection con, OrderItem item) throws SQLException {
QueryRunner r = new QueryRunner();
String sql ="insert into orderitem(price,amount,goods_id,order_id) values(?,?,?,?)";
r.update(con,sql,item.getPrice(),item.getAmount(),item.getGoods().getId(),item.getOrder().getId());
}
}
以上代码中,将用户订单信息添加至数据库的订单表后,通过数据库函数获得订单表的主键id,并保存至order对象中,然后将订单中的每一个商品的商品编号,价格和数量以及归属于哪一个订单中的订单编号插入至子订单表中。执行成功后,跳转至order_success.jsp页面,显示订单支付成功。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>支付成功</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="layer/layer.js"></script>
<script type="text/javascript" src="js/cart.js"></script>
</head>
<body>
<jsp:include page="header.jsp"></jsp:include>
<div class="cart-items">
<div class="container">
<c:if test="${!empty msg }">
<div class="alert alert-success">${msg }</div>
</c:if>
<p><a class="btn btn-success" href="/order_list">查看我的订单</a></p>
</div>
</div>
<jsp:include page="footer.jsp"></jsp:include>
</body>
</html>
订单支付成功后,购物车也会清空。