程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> javaweb圖書商城設計之用戶模塊(1)

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

編輯:關於JAVA

javaweb圖書商城設計之用戶模塊(1)。本站提示廣大學習愛好者:(javaweb圖書商城設計之用戶模塊(1))文章只能為提供參考,不一定能成為您想要的結果。以下是javaweb圖書商城設計之用戶模塊(1)正文


本文次要為大家剖析了圖書商城的用戶模塊,詳細內容如下

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 >${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 >${errors.username }</span>
 <br/>
 密 碼:<input type="password" name="password" value="${form.password }"/>
 <span >${errors.password }</span>
 <br/>
 郵 箱:<input type="text" name="email" value="${form.email }"/>
 <span >${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

4、

用戶登錄

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

5、

用戶加入

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

quit():把session銷毀!

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved