国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

javaweb圖書商城設計之用戶模塊(1)

2019-11-26 13:34:51
字體:
來源:轉載
供稿:網友

本文主要為大家分析了圖書商城的用戶模塊,具體內容如下

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("http://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

4、

用戶登錄

流程:/jsps/user/login.jsp -> UserServlet#login() -> index.jsp

5、

用戶退出

流程:top.jsp -> UserServlet#quit() -> login.jsp

quit():把session銷毀!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 麟游县| 关岭| 山丹县| 甘德县| 辛集市| 托里县| 丽江市| 大庆市| 潜江市| 滕州市| 曲阜市| 云霄县| 招远市| 靖边县| 德江县| 仙游县| 普宁市| 土默特左旗| 乐至县| 南平市| 承德市| 原阳县| 阳春市| 沙湾县| 钟祥市| 呼伦贝尔市| 喀喇沁旗| 宣恩县| 天等县| 云林县| 桦川县| 台北县| 正定县| 宜兰市| 遂川县| 遵义县| 建水县| 聂拉木县| 通州区| 当阳市| 贡觉县|