javaweb圖書商城設(shè)計之用戶模塊(1)
本文主要為大家分析了圖書商城的用戶模塊,具體內(nèi)容如下
1、用戶模塊的相關(guān)類創(chuàng)建
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的領(lǐng)域?qū)ο? */ public class User { /* * 對應(yīng)數(shù)據(jù)庫表 */ private String uid;// 主鍵 private String username;// 用戶名 private String password;// 密碼 private String email;// 郵箱 private String code;// 激活碼 private boolean state;// 狀態(tài)(已激活和未激活)
BaseServlet
public class BaseServlet extends HttpServlet { /* * 它會根據(jù)請求中的method,來決定調(diào)用本類的哪個方法 */ 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. 封裝表單數(shù)據(jù)到form中 * 2. 輸入校驗(不寫了) * 3. 調(diào)用service完成激活 * > 保存錯誤信息、form到request,轉(zhuǎn)發(fā)到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. 獲取參數(shù)激活碼 * 2. 調(diào)用service方法完成激活 * > 保存異常信息到request域,轉(zhuǎn)發(fā)到msg.jsp * 3. 保存成功信息到request域,轉(zhuǎn)發(fā)到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. 封裝表單數(shù)據(jù)到form對象中 * 2. 補全:uid、code * 3. 輸入校驗 * > 保存錯誤信息、form到request域,轉(zhuǎn)發(fā)到regist.jsp * 4. 調(diào)用service方法完成注冊 * > 保存錯誤信息、form到request域,轉(zhuǎn)發(fā)到regist.jsp * 5. 發(fā)郵件 * 6. 保存成功信息轉(zhuǎn)發(fā)到msg.jsp */ // 封裝表單數(shù)據(jù) User form = CommonUtils.toBean(request.getParameterMap(), User.class); // 補全 form.setUid(CommonUtils.uuid()); form.setCode(CommonUtils.uuid() + CommonUtils.uuid()); /* * 輸入校驗 * 1. 創(chuàng)建一個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. 保存表單數(shù)據(jù) // 3. 轉(zhuǎn)發(fā)到regist.jsp request.setAttribute("errors", errors); request.setAttribute("form", form); return "f:/jsps/user/regist.jsp"; } /* * 調(diào)用service的regist()方法 */ try { userService.regist(form); } catch (UserException e) { /* * 1. 保存異常信息 * 2. 保存form * 3. 轉(zhuǎn)發(fā)到regist.jsp */ request.setAttribute("msg", e.getMessage()); request.setAttribute("form", form); return "f:/jsps/user/regist.jsp"; } /* * 發(fā)郵件 * 準備配置文件! */ // 獲取配置文件內(nèi)容 Properties props = new Properties(); props.load(this.getClass().getClassLoader() .getResourceAsStream("email_template.properties")); String host = props.getProperty("host");//獲取服務(wù)器主機 String uname = props.getProperty("uname");//獲取用戶名 String pwd = props.getProperty("pwd");//獲取密碼 String from = props.getProperty("from");//獲取發(fā)件人 String to = form.getEmail();//獲取收件人 String subject = props.getProperty("subject");//獲取主題 String content = props.getProperty("content");//獲取郵件內(nèi)容 content = MessageFormat.format(content, form.getCode());//替換{0} Session session = MailUtils.createSession(host, uname, pwd);//得到session Mail mail = new Mail(from, to, subject, content);//創(chuàng)建郵件對象 try { MailUtils.send(session, mail);//發(fā)郵件! } catch (MessagingException e) { } /* * 1. 保存成功信息 * 2. 轉(zhuǎn)發(fā)到msg.jsp */ request.setAttribute("msg", "恭喜,注冊成功!請馬上到郵箱激活"); return "f:/jsps/msg.jsp"; } }
2.4 UserService
/** * User業(yè)務(wù)層 */ 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已被注冊!"); // 插入用戶到數(shù)據(jù)庫 userDao.add(form); } /** * 激活功能 * @throws UserException */ public void active(String code) throws UserException { /* * 1. 使用code查詢數(shù)據(jù)庫,得到user */ User user = userDao.findByCode(code); /* * 2. 如果user不存在,說明激活碼錯誤 */ if(user == null) throw new UserException("激活碼無效!"); /* * 3. 校驗用戶的狀態(tài)是否為未激活狀態(tài),如果已激活,說明是二次激活,拋出異常 */ if(user.isState()) throw new UserException("您已經(jīng)激活過了,不要再激活了,除非你想死!"); /* * 4. 修改用戶的狀態(tài) */ 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. 查看用戶的狀態(tài),若為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); } } /** * 修改指定用戶的指定狀態(tài) * @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
4、
用戶登錄
流程:/jsps/user/login.jsp -> UserServlet#login() -> index.jsp
5、
用戶退出
流程:top.jsp -> UserServlet#quit() -> login.jsp
quit():把session銷毀!
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于java TCP網(wǎng)絡(luò)通信的實例詳解
本篇文章是對java中TCP網(wǎng)絡(luò)通信的實例進行了詳細的分析介紹,需要的朋友參考下2013-05-05java中使用try-catch-finally一些值得注意的事(必看)
下面小編就為大家?guī)硪黄猨ava中使用try-catch-finally一些值得注意的事(必看)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08在IDEA中 實現(xiàn)給main方法附帶參數(shù)的操作
這篇文章主要介紹了在IDEA中 實現(xiàn)給main方法附帶參數(shù)的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01SpringBoot集成minio實現(xiàn)文件上傳和刪除功能
這篇文章主要介紹了SpringBoot集成minio實現(xiàn)文件上傳和刪除功能,詳細介紹每個功能的實現(xiàn)步驟和代碼示例,具有一定的參考價值,感興趣的可以了解一下2023-11-11SpringCloud Zuul過濾器實現(xiàn)登陸鑒權(quán)代碼實例
這篇文章主要介紹了SpringCloud Zuul過濾器實現(xiàn)登陸鑒權(quán)代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03Java內(nèi)存之happens-before和重排序
在JMM(Java內(nèi)存模型)中,如果一個操作執(zhí)行的結(jié)果需要對另一個操作可見,那么這兩個操作之間必須存在happens-before關(guān)系。下面小編來簡單介紹一下2019-05-05