- Servlet+mysql实现的书城系统
- 实现功能截图
- 实现的功能
- 使用技术
- 代码
- 写在最后
本系统为书城系统,分为前后台,前台通过各类畅销书展示,用户可以购买图书、加入购物车结算,后台管理系统,可以进行图书录入上架、图书分类管理、订单管理等,一整套完整的图书电商系统。
实现功能截图前台:
登录
图书购买
提交订单
后台
首页
分类管理
订单管理
前台:
1、登录
2、图书分类展示
3、图书购买加入购物车
4、提交订单
5、结算
后台
1、订单管理
2、分类管理
3、图书上架
数据库:mysql
开发工具:Eclipse(Myeclispe、Idea也可以)
知识点:Servlet、Jsp
本系统采用将MVC的思想:将项目包分为pojo、dao/service/controller,代码结构清晰
代码dao
UserDao.java
package cn.itcast.goods.user.dao;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import cn.itcast.goods.user.domain.User;
import cn.itcast.jdbc.TxQueryRunner;
/**
* 用户模块持久层
* @author qdmmy6
*
*/
public class UserDao {
private QueryRunner qr = new TxQueryRunner();
/**
* 按uid和password查询
* @param uid
* @param password
* @return
* @throws SQLException
*/
public boolean findByUidAndPassword(String uid, String password) throws SQLException {
String sql = "select count(*) from t_user where uid=? and loginpass=?";
Number number = (Number)qr.query(sql, new ScalarHandler(), uid, password);
return number.intValue() > 0;
}
/**
* 修改密码
* @param uid
* @param password
* @throws SQLException
*/
public void updatePassword(String uid, String password) throws SQLException {
String sql = "update t_user set loginpass=? where uid=?";
qr.update(sql, password, uid);
}
/**
* 按用户名和密码查询
* @param loginname
* @param loginpass
* @return
* @throws SQLException
*/
public User findByLoginnameAndLoginpass(String loginname, String loginpass) throws SQLException {
String sql = "select * from t_user where loginname=? and loginpass=?";
return qr.query(sql, new BeanHandler<User>(User.class), loginname, loginpass);
}
/**
* 通过激活码查询用户
* @param code
* @return
* @throws SQLException
*/
public User findByCode(String code) throws SQLException {
String sql = "select * from t_user where activationCode=?";
return qr.query(sql, new BeanHandler<User>(User.class), code);
}
/**
* 修改用户状态
* @param uid
* @param status
* @throws SQLException
*/
public void updateStatus(String uid, boolean status) throws SQLException {
String sql = "update t_user set status=? where uid=?";
qr.update(sql, status, uid);
}
/**
* 校验用户名是否注册
* @param loginname
* @return
* @throws SQLException
*/
public boolean ajaxValidateLoginname(String loginname) throws SQLException {
String sql = "select count(1) from t_user where loginname=?";
Number number = (Number)qr.query(sql, new ScalarHandler(), loginname);
return number.intValue() == 0;
}
/**
* 校验Email是否注册
* @param email
* @return
* @throws SQLException
*/
public boolean ajaxValidateEmail(String email) throws SQLException {
String sql = "select count(1) from t_user where email=?";
Number number = (Number)qr.query(sql, new ScalarHandler(), email);
return number.intValue() == 0;
}
/**
* 添加用户
* @param user
* @throws SQLException
*/
public void add(User user) throws SQLException {
String sql = "insert into t_user values(?,?,?,?,?,?)";
Object[] params = {user.getUid(), user.getLoginname(), user.getLoginpass(),
user.getEmail(), user.isStatus(), user.getActivationCode()};
qr.update(sql, params);
}
}
AdminDao.java
package cn.itcast.goods.admin.admin.dao;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import cn.itcast.goods.admin.admin.domain.Admin;
import cn.itcast.jdbc.TxQueryRunner;
public class AdminDao {
private QueryRunner qr = new TxQueryRunner();
/**
* 通过管理员登录名和登录密码查询
* @param adminname
* @param adminpwd
* @return
* @throws SQLException
*/
public Admin find(String adminname, String adminpwd) throws SQLException {
String sql = "select * from t_admin where adminname=? and adminpwd=?";
return qr.query(sql, new BeanHandler<Admin>(Admin.class), adminname, adminpwd);
}
}
service
AdminService.java
package cn.itcast.goods.admin.admin.service;
import java.sql.SQLException;
import cn.itcast.goods.admin.admin.dao.AdminDao;
import cn.itcast.goods.admin.admin.domain.Admin;
public class AdminService {
private AdminDao adminDao = new AdminDao();
/**
* 登录功能
* @param admin
* @return
*/
public Admin login(Admin admin) {
try {
return adminDao.find(admin.getAdminname(), admin.getAdminpwd());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
UserService.java
package cn.itcast.goods.user.service;
import java.io.IOException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.user.dao.UserDao;
import cn.itcast.goods.user.domain.User;
import cn.itcast.goods.user.service.exception.UserException;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;
/**
* 用户模块业务层
* @author qdmmy6
*
*/
public class UserService {
private UserDao userDao = new UserDao();
/**
* 修改密码
* @param uid
* @param newPass
* @param oldPass
* @throws UserException
*/
public void updatePassword(String uid, String newPass, String oldPass) throws UserException {
try {
/*
* 1. 校验老密码
*/
boolean bool = userDao.findByUidAndPassword(uid, oldPass);
if(!bool) {//如果老密码错误
throw new UserException("老密码错误!");
}
/*
* 2. 修改密码
*/
userDao.updatePassword(uid, newPass);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 登录功能
* @param user
* @return
*/
public User login(User user) {
try {
return userDao.findByLoginnameAndLoginpass(user.getLoginname(), user.getLoginpass());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 激活功能
* @param code
* @throws UserException
*/
public void activatioin(String code) throws UserException {
/*
* 1. 通过激活码查询用户
* 2. 如果User为null,说明是无效激活码,抛出异常,给出异常信息(无效激活码)
* 3. 查看用户状态是否为true,如果为true,抛出异常,给出异常信息(请不要二次激活)
* 4. 修改用户状态为true
*/
try {
User user = userDao.findByCode(code);
if(user == null) throw new UserException("无效的激活码!");
if(user.isStatus()) throw new UserException("您已经激活过了,不要二次激活!");
userDao.updateStatus(user.getUid(), true);//修改状态
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 用户名注册校验
* @param loginname
* @return
*/
public boolean ajaxValidateLoginname(String loginname) {
try {
return userDao.ajaxValidateLoginname(loginname);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* Email校验
* @param email
* @return
*/
public boolean ajaxValidateEmail(String email) {
try {
return userDao.ajaxValidateEmail(email);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 注册功能
* @param user
*/
public void regist(User user) {
/*
* 1. 数据的补齐
*/
user.setUid(CommonUtils.uuid());
user.setStatus(false);
user.setActivationCode(CommonUtils.uuid() + CommonUtils.uuid());
/*
* 2. 向数据库插入
*/
try {
userDao.add(user);
} catch (SQLException e) {
throw new RuntimeException(e);
}
/*
* 3. 发邮件
*/
/*
* 把配置文件内容加载到prop中
*/
Properties prop = new Properties();
try {
prop.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
} catch (IOException e1) {
throw new RuntimeException(e1);
}
/*
* 登录邮件服务器,得到session
*/
String host = prop.getProperty("host");//服务器主机名
String name = prop.getProperty("username");//登录名
String pass = prop.getProperty("password");//登录密码
Session session = MailUtils.createSession(host, name, pass);
/*
* 创建Mail对象
*/
String from = prop.getProperty("from");
String to = user.getEmail();
String subject = prop.getProperty("subject");
// MessageForm.format方法会把第一个参数中的{0},使用第二个参数来替换。
// 例如MessageFormat.format("你好{0}, 你{1}!", "张三", "去死吧"); 返回“你好张三,你去死吧!”
String content = MessageFormat.format(prop.getProperty("content"), user.getActivationCode());
Mail mail = new Mail(from, to, subject, content);
/*
* 发送邮件
*/
try {
MailUtils.send(session, mail);
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
servlet
UserServlet.java
package cn.itcast.goods.user.web.servlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.user.domain.User;
import cn.itcast.goods.user.service.UserService;
import cn.itcast.goods.user.service.exception.UserException;
import cn.itcast.servlet.BaseServlet;
/**
* 用户模块WEB层
* @author qdmmy6
*
*/
public class UserServlet extends BaseServlet {
private UserService userService = new UserService();
/**
* ajax用户名是否注册校验
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String ajaxValidateLoginname(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 获取用户名
*/
String loginname = req.getParameter("loginname");
/*
* 2. 通过service得到校验结果
*/
boolean b = userService.ajaxValidateLoginname(loginname);
/*
* 3. 发给客户端
*/
resp.getWriter().print(b);
return null;
}
/**
* ajax Email是否注册校验
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String ajaxValidateEmail(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 获取Email
*/
String email = req.getParameter("email");
/*
* 2. 通过service得到校验结果
*/
boolean b = userService.ajaxValidateEmail(email);
/*
* 3. 发给客户端
*/
resp.getWriter().print(b);
return null;
}
/**
* ajax验证码是否正确校验
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String ajaxValidateVerifyCode(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 获取输入框中的验证码
*/
String verifyCode = req.getParameter("verifyCode");
/*
* 2. 获取图片上真实的校验码
*/
String vcode = (String) req.getSession().getAttribute("vCode");
/*
* 3. 进行忽略大小写比较,得到结果
*/
boolean b = verifyCode.equalsIgnoreCase(vcode);
/*
* 4. 发送给客户端
*/
resp.getWriter().print(b);
return null;
}
/**
* 注册功能
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String regist(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 封装表单数据到User对象
*/
User formUser = CommonUtils.toBean(req.getParameterMap(), User.class);
/*
* 2. 校验之, 如果校验失败,保存错误信息,返回到regist.jsp显示
*/
Map<String,String> errors = validateRegist(formUser, req.getSession());
if(errors.size() > 0) {
req.setAttribute("form", formUser);
req.setAttribute("errors", errors);
return "f:/jsps/user/regist.jsp";
}
/*
* 3. 使用service完成业务
*/
userService.regist(formUser);
/*
* 4. 保存成功信息,转发到msg.jsp显示!
*/
req.setAttribute("code", "success");
req.setAttribute("msg", "注册功能,请马上到邮箱激活!");
return "f:/jsps/msg.jsp";
}
/*
* 注册校验
* 对表单的字段进行逐个校验,如果有错误,使用当前字段名称为key,错误信息为value,保存到map中
* 返回map
*/
private Map<String,String> validateRegist(User formUser, HttpSession session) {
Map<String,String> errors = new HashMap<String,String>();
/*
* 1. 校验登录名
*/
String loginname = formUser.getLoginname();
if(loginname == null || loginname.trim().isEmpty()) {
errors.put("loginname", "用户名不能为空!");
} else if(loginname.length() < 3 || loginname.length() > 20) {
errors.put("loginname", "用户名长度必须在3~20之间!");
} else if(!userService.ajaxValidateLoginname(loginname)) {
errors.put("loginname", "用户名已被注册!");
}
/*
* 2. 校验登录密码
*/
String loginpass = formUser.getLoginpass();
if(loginpass == null || loginpass.trim().isEmpty()) {
errors.put("loginpass", "密码不能为空!");
} else if(loginpass.length() < 3 || loginpass.length() > 20) {
errors.put("loginpass", "密码长度必须在3~20之间!");
}
/*
* 3. 确认密码校验
*/
String reloginpass = formUser.getReloginpass();
if(reloginpass == null || reloginpass.trim().isEmpty()) {
errors.put("reloginpass", "确认密码不能为空!");
} else if(!reloginpass.equals(loginpass)) {
errors.put("reloginpass", "两次输入不一致!");
}
/*
* 4. 校验email
*/
String email = formUser.getEmail();
if(email == null || email.trim().isEmpty()) {
errors.put("email", "Email不能为空!");
} else if(!email.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$")) {
errors.put("email", "Email格式错误!");
} else if(!userService.ajaxValidateEmail(email)) {
errors.put("email", "Email已被注册!");
}
/*
* 5. 验证码校验
*/
String verifyCode = formUser.getVerifyCode();
String vcode = (String) session.getAttribute("vCode");
if(verifyCode == null || verifyCode.trim().isEmpty()) {
errors.put("verifyCode", "验证码不能为空!");
} else if(!verifyCode.equalsIgnoreCase(vcode)) {
errors.put("verifyCode", "验证码错误!");
}
return errors;
}
/**
* 激活功能
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String activation(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 获取参数激活码
* 2. 用激活码调用service方法完成激活
* > service方法有可能抛出异常, 把异常信息拿来,保存到request中,转发到msg.jsp显示
* 3. 保存成功信息到request,转发到msg.jsp显示。
*/
String code = req.getParameter("activationCode");
try {
userService.activatioin(code);
req.setAttribute("code", "success");//通知msg.jsp显示对号
req.setAttribute("msg", "恭喜,激活成功,请马上登录!");
} catch (UserException e) {
// 说明service抛出了异常
req.setAttribute("msg", e.getMessage());
req.setAttribute("code", "error");//通知msg.jsp显示X
}
return "f:/jsps/msg.jsp";
}
/**
* 修改密码
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String updatePassword(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 封装表单数据到user中
* 2. 从session中获取uid
* 3. 使用uid和表单中的oldPass和newPass来调用service方法
* > 如果出现异常,保存异常信息到request中,转发到pwd.jsp
* 4. 保存成功信息到rquest中
* 5. 转发到msg.jsp
*/
User formUser = CommonUtils.toBean(req.getParameterMap(), User.class);
User user = (User)req.getSession().getAttribute("sessionUser");
// 如果用户没有登录,返回到登录页面,显示错误信息
if(user == null) {
req.setAttribute("msg", "您还没有登录!");
return "f:/jsps/user/login.jsp";
}
try {
userService.updatePassword(user.getUid(), formUser.getNewpass(),
formUser.getLoginpass());
req.setAttribute("msg", "修改密码成功");
req.setAttribute("code", "success");
return "f:/jsps/msg.jsp";
} catch (UserException e) {
req.setAttribute("msg", e.getMessage());//保存异常信息到request
req.setAttribute("user", formUser);//为了回显
return "f:/jsps/user/pwd.jsp";
}
}
/**
* 退出功能
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String quit(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.getSession().invalidate();
return "r:/jsps/user/login.jsp";
}
/**
* 登录功能
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String login(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 封装表单数据到User
* 2. 校验表单数据
* 3. 使用service查询,得到User
* 4. 查看用户是否存在,如果不存在:
* * 保存错误信息:用户名或密码错误
* * 保存用户数据:为了回显
* * 转发到login.jsp
* 5. 如果存在,查看状态,如果状态为false:
* * 保存错误信息:您没有激活
* * 保存表单数据:为了回显
* * 转发到login.jsp
* 6. 登录成功:
* * 保存当前查询出的user到session中
* * 保存当前用户的名称到cookie中,注意中文需要编码处理。
*/
/*
* 1. 封装表单数据到user
*/
User formUser = CommonUtils.toBean(req.getParameterMap(), User.class);
/*
* 2. 校验
*/
Map<String,String> errors = validateLogin(formUser, req.getSession());
if(errors.size() > 0) {
req.setAttribute("form", formUser);
req.setAttribute("errors", errors);
return "f:/jsps/user/login.jsp";
}
/*
* 3. 调用userService#login()方法
*/
User user = userService.login(formUser);
/*
* 4. 开始判断
*/
if(user == null) {
req.setAttribute("msg", "用户名或密码错误!");
req.setAttribute("user", formUser);
return "f:/jsps/user/login.jsp";
} else {
if(!user.isStatus()) {
req.setAttribute("msg", "您还没有激活!");
req.setAttribute("user", formUser);
return "f:/jsps/user/login.jsp";
} else {
// 保存用户到session
req.getSession().setAttribute("sessionUser", user);
// 获取用户名保存到cookie中
String loginname = user.getLoginname();
loginname = URLEncoder.encode(loginname, "utf-8");
Cookie cookie = new Cookie("loginname", loginname);
cookie.setMaxAge(60 * 60 * 24 * 10);//保存10天
resp.addCookie(cookie);
return "r:/index.jsp";//重定向到主页
}
}
}
/*
* 登录校验方法,内容等你自己来完成
*/
private Map<String,String> validateLogin(User formUser, HttpSession session) {
Map<String,String> errors = new HashMap<String,String>();
return errors;
}
}
CategoryServlet.java
package cn.itcast.goods.category.web.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.goods.category.domain.Category;
import cn.itcast.goods.category.service.CategoryService;
import cn.itcast.servlet.BaseServlet;
/**
* 分类模块WEB层
* @author qdmmy6
*
*/
public class CategoryServlet extends BaseServlet {
private CategoryService categoryService = new CategoryService();
/**
* 查询所有分类
*/
public String findAll(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 通过service得到所有的分类
* 2. 保存到request中,转发到left.jsp
*/
List<Category> parents = categoryService.findAll();
req.setAttribute("parents", parents);
return "f:/jsps/left.jsp";
}
}
写在最后
如果运行代码中遇到问题,或者需要完整源码和报告论文,可以加博主V交流:Code2Life2
觉得有用,别忘了一键三连哈!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)