javaweb图书商城设计之用户模块(1)
作者:Android-Dev 时间:2023-10-30 09:22:57
本文主要为大家分析了图书商城的用户模块,具体内容如下
1、用户模块的相关类创建
domain:User
dao:UserDao
service:UserDao
web.servlet:UserServlet
2、用户注册
2.1 注册流程
/jsps/user/regist.jsp -> UserServlet#regist() -> msg.jsp
2.2 注册页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>注册</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>注册</h1>
<%--
1. 显示errors --> 字段错误
2. 显示异常错误
3. 回显
--%>
<p style="color: red; font-weight: 900">${msg }</p>
<form action="<c:url value='/UserServlet'/>" method="post">
<input type="hidden" name="method" value="regist"/>
用户名:<input type="text" name="username" value="${form.username }"/>
<span style="color: red; font-weight: 900">${errors.username }</span>
<br/>
密码:<input type="password" name="password" value="${form.password }"/>
<span style="color: red; font-weight: 900">${errors.password }</span>
<br/>
邮箱:<input type="text" name="email" value="${form.email }"/>
<span style="color: red; font-weight: 900">${errors.email }</span>
<br/>
<input type="submit" value="注册"/>
</form>
</body>
</html>
2.3 UserServlet
User
/**
* User的领域对象
*/
public class User {
/*
* 对应数据库表
*/
private String uid;// 主键
private String username;// 用户名
private String password;// 密码
private String email;// 邮箱
private String code;// 激活码
private boolean state;// 状态(已激活和未激活)
BaseServlet
public class BaseServlet extends HttpServlet {
/*
* 它会根据请求中的method,来决定调用本类的哪个方法
*/
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=utf-8");
try {
// 例如:http://localhost:8080/demo1/xxx?m=add
String method = req.getParameter("method");// 它是一个方法名称
Class c = this.getClass();
Method m = c.getMethod(method, HttpServletRequest.class,
HttpServletResponse.class);
String result = (String) m.invoke(this, req, res);
if(result != null && !result.isEmpty()) {
req.getRequestDispatcher(result).forward(req, res);
}
} catch (Exception e) {
throw new ServletException(e);
}
}
}
UserServlet
/**
* User表述层
*/
public class UserServlet extends BaseServlet {
private UserService userService = new UserService();
/**
* 退出功能
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public String quit(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getSession().invalidate();
return "r:/index.jsp";
}
public String login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* 1. 封装表单数据到form中
* 2. 输入校验(不写了)
* 3. 调用service完成激活
* > 保存错误信息、form到request,转发到login.jsp
* 4. 保存用户信息到session中,然后重定向到index.jsp
*/
User form = CommonUtils.toBean(request.getParameterMap(), User.class);
try {
User user = userService.login(form);
request.getSession().setAttribute("session_user", user);
/*
* 给用户添加一个购物车,即向session中保存一Cart对象
*/
request.getSession().setAttribute("cart", new Cart());
return "r:/index.jsp";
} catch (UserException e) {
request.setAttribute("msg", e.getMessage());
request.setAttribute("form", form);
return "f:/jsps/user/login.jsp";
}
}
/**
* 激活功能
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public String active(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* 1. 获取参数激活码
* 2. 调用service方法完成激活
* > 保存异常信息到request域,转发到msg.jsp
* 3. 保存成功信息到request域,转发到msg.jsp
*/
String code = request.getParameter("code");
try {
userService.active(code);
request.setAttribute("msg", "恭喜,您激活成功了!请马上登录!");
} catch (UserException e) {
request.setAttribute("msg", e.getMessage());
}
return "f:/jsps/msg.jsp";
}
/**
* 注册功能
* @param request
* @param response
* @return
* @throws ServletException
* @throws IOException
*/
public String regist(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* 1. 封装表单数据到form对象中
* 2. 补全:uid、code
* 3. 输入校验
* > 保存错误信息、form到request域,转发到regist.jsp
* 4. 调用service方法完成注册
* > 保存错误信息、form到request域,转发到regist.jsp
* 5. 发邮件
* 6. 保存成功信息转发到msg.jsp
*/
// 封装表单数据
User form = CommonUtils.toBean(request.getParameterMap(), User.class);
// 补全
form.setUid(CommonUtils.uuid());
form.setCode(CommonUtils.uuid() + CommonUtils.uuid());
/*
* 输入校验
* 1. 创建一个Map,用来封装错误信息,其中key为表单字段名称,值为错误信息
*/
Map<String,String> errors = new HashMap<String,String>();
/*
* 2. 获取form中的username、password、email进行校验
*/
String username = form.getUsername();
if(username == null || username.trim().isEmpty()) {
errors.put("username", "用户名不能为空!");
} else if(username.length() < 3 || username.length() > 10) {
errors.put("username", "用户名长度必须在3~10之间!");
}
String password = form.getPassword();
if(password == null || password.trim().isEmpty()) {
errors.put("password", "密码不能为空!");
} else if(password.length() < 3 || password.length() > 10) {
errors.put("password", "密码长度必须在3~10之间!");
}
String email = form.getEmail();
if(email == null || email.trim().isEmpty()) {
errors.put("email", "Email不能为空!");
} else if(!email.matches("\\w+@\\w+\\.\\w+")) {
errors.put("email", "Email格式错误!");
}
/*
* 3. 判断是否存在错误信息
*/
if(errors.size() > 0) {
// 1. 保存错误信息
// 2. 保存表单数据
// 3. 转发到regist.jsp
request.setAttribute("errors", errors);
request.setAttribute("form", form);
return "f:/jsps/user/regist.jsp";
}
/*
* 调用service的regist()方法
*/
try {
userService.regist(form);
} catch (UserException e) {
/*
* 1. 保存异常信息
* 2. 保存form
* 3. 转发到regist.jsp
*/
request.setAttribute("msg", e.getMessage());
request.setAttribute("form", form);
return "f:/jsps/user/regist.jsp";
}
/*
* 发邮件
* 准备配置文件!
*/
// 获取配置文件内容
Properties props = new Properties();
props.load(this.getClass().getClassLoader()
.getResourceAsStream("email_template.properties"));
String host = props.getProperty("host");//获取服务器主机
String uname = props.getProperty("uname");//获取用户名
String pwd = props.getProperty("pwd");//获取密码
String from = props.getProperty("from");//获取发件人
String to = form.getEmail();//获取收件人
String subject = props.getProperty("subject");//获取主题
String content = props.getProperty("content");//获取邮件内容
content = MessageFormat.format(content, form.getCode());//替换{0}
Session session = MailUtils.createSession(host, uname, pwd);//得到session
Mail mail = new Mail(from, to, subject, content);//创建邮件对象
try {
MailUtils.send(session, mail);//发邮件!
} catch (MessagingException e) {
}
/*
* 1. 保存成功信息
* 2. 转发到msg.jsp
*/
request.setAttribute("msg", "恭喜,注册成功!请马上到邮箱激活");
return "f:/jsps/msg.jsp";
}
}
2.4 UserService
/**
* User业务层
*/
public class UserService {
private UserDao userDao = new UserDao();
/**
* 注册功能
* @param form
*/
public void regist(User form) throws UserException{
// 校验用户名
User user = userDao.findByUsername(form.getUsername());
if(user != null) throw new UserException("用户名已被注册!");
// 校验email
user = userDao.findByEmail(form.getEmail());
if(user != null) throw new UserException("Email已被注册!");
// 插入用户到数据库
userDao.add(form);
}
/**
* 激活功能
* @throws UserException
*/
public void active(String code) throws UserException {
/*
* 1. 使用code查询数据库,得到user
*/
User user = userDao.findByCode(code);
/*
* 2. 如果user不存在,说明激活码错误
*/
if(user == null) throw new UserException("激活码无效!");
/*
* 3. 校验用户的状态是否为未激活状态,如果已激活,说明是二次激活,抛出异常
*/
if(user.isState()) throw new UserException("您已经激活过了,不要再激活了,除非你想死!");
/*
* 4. 修改用户的状态
*/
userDao.updateState(user.getUid(), true);
}
/**
* 登录功能
* @param form
* @return
* @throws UserException
*/
public User login(User form) throws UserException {
/*
* 1. 使用username查询,得到User
* 2. 如果user为null,抛出异常(用户名不存在)
* 3. 比较form和user的密码,若不同,抛出异常(密码错误)
* 4. 查看用户的状态,若为false,抛出异常(尚未激活)
* 5. 返回user
*/
User user = userDao.findByUsername(form.getUsername());
if(user == null) throw new UserException("用户名不存在!");
if(!user.getPassword().equals(form.getPassword()))
throw new UserException("密码错误!");
if(!user.isState()) throw new UserException("尚未激活!");
return user;
}
}
2.5 UserDao
/**
* User持久层
*/
public class UserDao {
private QueryRunner qr = new TxQueryRunner();
/**
* 按用户名查询
* @param username
* @return
*/
public User findByUsername(String username) {
try {
String sql = "select * from tb_user where username=?";
return qr.query(sql, new BeanHandler<User>(User.class), username);
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 按email查询
* @param email
* @return
*/
public User findByEmail(String email) {
try {
String sql = "select * from tb_user where email=?";
return qr.query(sql, new BeanHandler<User>(User.class), email);
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 插入User
* @param user
*/
public void add(User user) {
try {
String sql = "insert into tb_user values(?,?,?,?,?,?)";
Object[] params = {user.getUid(), user.getUsername(),
user.getPassword(), user.getEmail(), user.getCode(),
user.isState()};
qr.update(sql, params);
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 按激活码查询
* @param code
* @return
*/
public User findByCode(String code) {
try {
String sql = "select * from tb_user where code=?";
return qr.query(sql, new BeanHandler<User>(User.class), code);
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 修改指定用户的指定状态
* @param uid
* @param state
*/
public void updateState(String uid, boolean state) {
try {
String sql = "update tb_user set state=? where uid=?";
qr.update(sql, state, uid);
} catch(SQLException e) {
throw new RuntimeException(e);
}
}
}
3、用户激活
流程:用户的邮件中 -> UserServlet#active() -> msg.jsp
用户登录
流程:/jsps/user/login.jsp -> UserServlet#login() -> index.jsp
用户退出
流程:top.jsp -> UserServlet#quit() -> login.jsp
quit():把session销毁!
标签:javaweb,图书商城
0
投稿
猜你喜欢
springdata jpa使用Example快速实现动态查询功能
2022-12-01 21:49:08
在Parallel中使用DbSet.Add()发现的一系列多线程问题和解决思路详解
2023-02-13 19:31:10
Android 获取 usb 权限的两种方法
2022-01-06 14:37:06
在Android中如何使用DataBinding详解(Kotlin)
2022-12-17 15:09:51
Java 抽象类定义与方法实例详解
2022-10-20 09:26:38
Android水波纹载入控件CircleWaterWaveView使用详解
2021-10-27 23:06:58
Java实现读写文件功能的代码分享
2023-02-07 04:07:02
SpringBoot整合Swagger2的步骤详解
2021-07-19 11:59:49
Java汉字转拼音工具类完整代码实例
2021-07-09 21:32:18
Android中的HOOK技术是什么
2022-06-19 18:18:24
简单理解Java的垃圾回收机制与finalize方法的作用
2023-02-04 01:49:37
idea 创建 maven web 工程流程(图文教程)
2022-06-29 04:51:21
java开发之闹钟的实现代码
2021-07-08 12:46:49
Java中计算时间差的方法
2023-11-15 10:35:44
Android自定义processor实现bindView功能的实例
2023-09-07 17:16:37
android gradle如何修改生成的apk名字
2023-03-09 23:38:56
Spring注解驱动开发实现属性赋值
2023-05-07 04:40:22
Java实现二分查找算法实例分析
2022-06-01 07:30:32
Android使用CountDownTimer模拟短信验证倒计时
2022-10-24 18:00:28
c#多线程程序设计实例方法
2023-07-24 16:39:28