1、我們來看看后台操作的業務流程
每一層都按照上面的步驟來進行實現:
這里我們要使用commUtils.toBean把表單提交的參數封裝成User對象,必須保證User對象中的字段和表單提交的字段的名稱是一模一樣的
<tr>
<td align="right">新密碼:</td>
<td><input class="input" type="password" name="newpass" id="newpass" value=""/></td>
<td><label id="newpassError" class="error"></label></td>
</tr>
這里對應的是newpass,那么User對象的字段也必須是newpass
package com.weiyuan.goods.user.domian;
public class User {
private String uid; //主鍵
private String loginname;// 登陸名稱
private String loginpass;// 登陸密碼
private String email;//注冊的郵箱
private String verifyCode; //驗證碼
private int status;//是否激活
private String activationCode;//激活碼
//增加下面的幾個字段
private String reloginpass; //確認密碼
private String newpass;//修改密碼對應的新密碼
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getReloginpass() {
return reloginpass;
}
public void setReloginpass(String reloginpass) {
this.reloginpass = reloginpass;
}
public String getNewpass() {
return newpass;
}
public void setNewpass(String newpass) {
this.newpass = newpass;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getLoginname() {
return loginname;
}
public void setLoginname(String loginname) {
this.loginname = loginname;
}
public String getLoginpass() {
return loginpass;
}
public void setLoginpass(String loginpass) {
this.loginpass = loginpass;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getVerifyCode() {
return verifyCode;
}
public void setVerifyCode(String verifyCode) {
this.verifyCode = verifyCode;
}
public String getActivationCode() {
return activationCode;
}
public void setActivationCode(String activationCode) {
this.activationCode = activationCode;
}
@Override
public String toString() {
return "User [uid=" + uid + ", loginname=" + loginname + ", loginpass="
+ loginpass + ", email=" + email + ", verifyCode=" + verifyCode
+ ", status=" + status + ", activationCode=" + activationCode
+ "]";
}
}
我們來看看dao層的代碼:
package com.weiyuan.goods.user.dao; import java.sql.SQLException; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import com.weiyuan.goods.user.domian.User; import cn.itcast.jdbc.TxQueryRunner; public class UserDao { //操作數據庫 private TxQueryRunner qr = new TxQueryRunner(); /*** * 查詢用戶名是否存在 * @throws SQLException */ public boolean ajaxValidateLoginName(String loginName) throws SQLException{ //獲得滿足記錄的數目是對象,返回一個整數,整數是單行單列使用ScalarHandler String sql ="select count(*) from t_user where loginname=?"; Number num = (Number) qr.query(sql, new ScalarHandler(),loginName); int count = num.intValue(); if(count>0){ return true; } return false; } /*** * 查詢郵箱是否存在 * @throws SQLException */ public boolean ajaxValidateEmail(String email) throws SQLException{ //獲得滿足記錄的數目是對象,返回一個整數,整數是單行單列使用ScalarHandler String sql ="select count(*) from t_user where email=?"; Number num = (Number) qr.query(sql, new ScalarHandler(),email); int count = num.intValue(); System.out.println("count="+count); if(count>0){ return true; } return false; } /*** * 添加注冊的用戶 * @throws SQLException */ public void addUser(User user) throws SQLException{ //獲得滿足記錄的數目是對象,返回一個整數,整數是單行單列使用ScalarHandler String sql ="insert into t_user values(?,?,?,?,?,?)"; System.out.println("user="+user.toString()); Object[] params = {user.getUid(),user.getLoginname(),user.getLoginpass(), user.getEmail(),user.getStatus(),user.getActivationCode()}; qr.update(sql, params); } /* * 通過激活碼獲得用戶 * */ public User findUserByActivationCode(String activationCode) throws SQLException{ String sql = "select * from t_user where activationCode = ?"; return qr.query(sql, new BeanHandler<User>(User.class),activationCode); } /* * 設置用戶的激活狀態 * */ public void setUserActivationCode(String uuid,int status) throws SQLException{ String sql = "update t_user set status = ? where uid = ? "; qr.update(sql,status,uuid); } /* * 通過用戶名和密碼查找得到對應的用戶 * */ public User findUserByLoginnameAndPass(String loginName,String pass) throws SQLException{ String sql = "select * from t_user where loginname = ? and loginpass = ?"; return qr.query(sql, new BeanHandler<User>(User.class),loginName,pass); } /* * 通過uid和登陸密碼查找對應的用戶 * **/ public Boolean findUserByUidAndLoginPass(String uid,String loginPass) throws SQLException{ String sql = "select count(*) from t_user where uid = ? and loginpass = ?"; Number num = (Number) qr.query(sql, new ScalarHandler(),uid,loginPass); if(num.intValue() > 0){ return true; }else{ return false; } } /*修改用戶的密碼*/ public void updateUserPassword(String uid,String newPass) throws SQLException{ String sql = "update t_user set loginpass = ? where uid = ?"; qr.update(sql,newPass,uid); } }
我們來看看業務層的代碼:
package com.weiyuan.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 javax.management.RuntimeErrorException; import cn.itcast.commons.CommonUtils; import cn.itcast.mail.Mail; import cn.itcast.mail.MailUtils; import com.weiyuan.goods.user.dao.UserDao; import com.weiyuan.goods.user.domian.User; public class UserService { private UserDao dao = new UserDao(); public boolean ajaxValidateLoginName(String loginName) { try { return dao.ajaxValidateLoginName(loginName); } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e.getMessage()); } } public boolean ajaxValidateEmail(String email) { try { return dao.ajaxValidateEmail(email); } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e.getMessage()); } } //添加注冊的用戶 public void addUser(User user){ //添加用戶的uuid user.setUid(CommonUtils.uuid()); //添加用戶的激活碼 String activationCode = CommonUtils.uuid()+CommonUtils.uuid(); user.setActivationCode(activationCode); //當前處於未激活的狀態 user.setStatus(0);//0表示未激活 try { dao.addUser(user); } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e.getMessage()); } //向注冊的用戶發送郵件 //1讀取配置文件 Properties properties = new Properties(); try { properties.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties")); } catch (IOException e1) { throw new RuntimeException(e1.getMessage()); } String host = properties.getProperty("host"); //qq郵箱發送郵件的地址,端口465或者587 //qq接受郵件服務器的地址是pop.qq.com,端口995 String username=properties.getProperty("username"); //登陸服務器的賬號 String password=properties.getProperty("password");//這里不是客戶端登陸的密碼,而是授權密碼一定要注意 Session session = MailUtils.createSession(host, username, password); //發送郵件 String from = properties.getProperty("from");//發件人 String to = user.getEmail();//收件人 String title = properties.getProperty("subject"); String content = properties.getProperty("content"); Object [] array = new Object[]{user.getActivationCode()}; //替換占位符 String formatContent = MessageFormat.format(content, user.getActivationCode());//替換占位符 System.out.println("email content is:"+content); Mail mail = new Mail(from,to,title,formatContent); try { MailUtils.send(session, mail); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } /*設置用戶的激活狀態*/ public void activation(String activationCode) throws Exception{ //1 、通過激活碼查找對應的用戶信息 try { User user = dao.findUserByActivationCode(activationCode); if(user == null){ throw new Exception("無效的激活碼");//業務異常,業務失敗 } if(user.getStatus()== 1){ throw new Exception("用戶已經既激活,不要二次激活");//業務異常,業務失敗 } dao.setUserActivationCode(user.getUid(), 1); //1表示激活 } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e.getMessage()); // 不是業務的異常嗎,而是電腦環境系統數據庫的異常,直接退出線程,無法進行業務的操作了 } } /* * 用戶登錄的業務操作,這里傳遞的參數是一個User對象 * */ public User login(User user){ try { return dao.findUserByLoginnameAndPass(user.getLoginname(),user.getLoginpass()); } catch (SQLException e) { throw new RuntimeException(e.getMessage()); } } /*修改用戶的密碼*/ public void updateUserPassword(String uid ,String oldPass,String newPass) throws Exception{ // 1、查找用戶是否存在 try { Boolean flag = dao.findUserByUidAndLoginPass(uid, oldPass); if(!flag){ throw new Exception("輸入的原始密碼有誤,請重新輸入"); } // 2、修改用戶的密碼 dao.updateUserPassword(uid, newPass); } catch (SQLException e) { throw new RuntimeException(e.getMessage()); } } }
我們來看看用戶控制層Servlet的代碼
當用戶點擊
package com.weiyuan.goods.user.web.servlet; import java.io.IOException; import java.net.URLEncoder; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.map.HashedMap; import com.weiyuan.goods.user.domian.User; import com.weiyuan.goods.user.service.UserService; import cn.itcast.commons.CommonUtils; import cn.itcast.servlet.BaseServlet; /** * Servlet implementation class UserServlet */ @WebServlet("/UserServlet") public class UserServlet extends BaseServlet{ private static final long serialVersionUID = 1L; private UserService service = new UserService(); /* * 用戶注冊頁面使用ajax校驗/* * 用戶注冊頁面使用ajax校驗用戶名會調用該方法 * *會調用該方法 * */ public String validateLoginname(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //首先獲得用戶上傳的用戶名 String loginName = request.getParameter("loginname"); boolean flag = service.ajaxValidateLoginName(loginName); response.getWriter().print(flag); return null; } /* * 用戶注冊頁面使用ajax校驗郵箱會調用該方法 * */ public String validateEmail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //獲得用戶上傳的emai String email = request.getParameter("email"); System.out.println("validateEmail is called"+email); boolean flag = service.ajaxValidateEmail(email); response.getWriter().print(flag); return null; } /* * 用戶修改密碼頁面使用ajax校驗原始的密碼是否正確 * */ public String validateLoginpass(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //獲得用戶上傳的emai String loginpass = request.getParameter("loginpass"); boolean flag = service.ajaxValidateLoginPass(loginpass); response.getWriter().print(flag); return null; } /* * 用戶注冊頁面使用ajax校驗驗證碼會調用該方法 * */ public String validateVerifyCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //獲得用戶上傳的verfycode String verifyCode = request.getParameter("verifyCode"); //獲得session中保存的驗證碼 String sessionCode = (String) request.getSession().getAttribute("vCode"); //二者進行比較看是否相等 System.out.println("validateVerifyCode is called"+verifyCode+":"+sessionCode); boolean flag = sessionCode.equalsIgnoreCase(verifyCode); response.getWriter().print(flag); return null; } /* * 當用戶從郵箱點擊的激活的時候會調用該方法,並且把激活碼傳遞過來 * * */ public String activation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String activationCode = request.getParameter("activationCode"); System.out.println("email activationCode is :"+activationCode); try { service.activation(activationCode); //激活成功 request.setAttribute("code", "success"); //msg.jsp已經code的值來顯示錯誤信息還是正確的信息 request.setAttribute("msg", "激活成功"); return "f:/jsps/msg.jsp"; } catch (Exception e) { //將業務操作的異常信息在msg.jsp中顯示出來 String msg = e.getMessage(); request.setAttribute("code", "error"); //msg.jsp已經code的值來顯示錯誤信息還是正確的信息 request.setAttribute("msg", msg); return "f:/jsps/msg.jsp"; } } /* * 當用戶注冊的時候會調用該方法 * * */ public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("activation is called"); //1、將請求的參數封裝成User對象 User user = CommonUtils.toBean(request.getParameterMap(), User.class); //2 、對傳遞過來的參數進行校驗,把錯誤的信息封裝到一個hashMap中 Map errors = validateParams(user, request); if(errors.size() > 0){//說明參數錯誤,跳轉到注冊界面提示用戶輸入的參數有誤 request.setAttribute("errors", errors); request.setAttribute("user", user); return "f:/jsps/user/regist.jsp"; } service.addUser(user); request.setAttribute("code", "success"); request.setAttribute("msg", "用戶注冊成功,請馬上到郵箱進行激活"); return "f:/jsps/msg.jsp"; } /* * 當用戶登錄的時候會調用該方法 * * */ public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("activation is called"); /*1、第一步將用戶提交的參數封裝成javabean對象 * *2、對提交的參數的進行合法性的校驗 * *3、通過用戶名和密碼去查找得到user對象 *如果user對象為null,說明用戶名和密碼不正確,重定向到login.jsp提示用戶名和密碼錯誤 *如果user對象不為null,查看當前用戶的激活狀態,如果當前用戶沒有被激活,提示當前用戶沒有被激活,重定向到login.jsp提示 *如果user對象不為null,並且當前用戶處於激活狀態,把當前用戶保存到session中,顯示當前用戶是誰 *為了實現頁面自定功能,需要把用戶名保存到cookie中,主要cookie不支持中文,需要對 *中文進行有效性的處理。 * * * * */ User formUser = CommonUtils.toBean(request.getParameterMap(), User.class); //對參數進行合法性的校驗 //2 、對傳遞過來的參數進行校驗,把錯誤的信息封裝到一個hashMap中 Map errors = validateLoginParams(formUser, request); if(errors.size() > 0){//說明參數錯誤,跳轉到注冊界面提示用戶輸入的參數有誤 request.setAttribute("errors", errors); request.setAttribute("user", formUser); return "f:/jsps/user/login.jsp"; } User user =service.login(formUser); //判斷用戶是否為null if(user == null){ request.setAttribute("msg", "輸入的用戶名和密碼不正確"); request.setAttribute("user", formUser); return "f:/jsps/user/login.jsp"; }else{ if(0 == user.getStatus()){ //沒有激活 request.setAttribute("msg", "當前用戶沒有激活,請先激活該用戶"); request.setAttribute("user", formUser); return "f:/jsps/user/login.jsp"; } //說明用戶登錄成功 request.getSession().setAttribute("sessionUser", user); //將用戶名保存到cookie中,因為cookie不支持中文使用URL進行編碼 Cookie cookie = new Cookie("cookieLoginName", URLEncoder.encode(user.getLoginname(), "utf-8")); cookie.setMaxAge(60*60*24);//cookie的有效期是一天 //添加cookie對象,把cookier對象返回給瀏覽器 response.addCookie(cookie); //登錄成功之后客戶端使用redict重新登錄到index.jsp主頁面 return "r:/index.jsp"; } } public Map validateParams(User user,HttpServletRequest request){ Map<String, String> map = new HashedMap(); //校驗用戶名 String loginName = user.getLoginname(); if(loginName == null || loginName.isEmpty()){ map.put("loginname", "用戶名不能為空"); } if(loginName.length() < 3 || loginName.length() > 20){ map.put("loginname", "用戶名長度應該在3到20之間"); } //校驗用戶名是否注冊 if(service.ajaxValidateLoginName(loginName)){ map.put("loginname", "用戶名已經被注冊"); } //檢查登陸密碼 String loginpass = user.getLoginpass(); if(loginpass == null || loginpass.isEmpty()){ map.put("loginpass", "登陸密碼不能為空"); } if(loginpass.length() < 3 || loginpass.length() > 20){ map.put("loginname", "登陸密碼的長度應該在3到20之間"); } //檢查確認密碼的信息 //檢查登陸密碼 String reloginpass = user.getReloginpass(); if(reloginpass == null || reloginpass.isEmpty()){ map.put("reloginpass", "登陸密碼不能為空"); } if(reloginpass.length() < 3 || reloginpass.length() > 20){ map.put("reloginpass", "登陸密碼的長度應該在3到20之間"); } if(!reloginpass.equalsIgnoreCase(loginpass)){ map.put("reloginpass", "兩次輸入的密碼不一樣"); } //檢查郵箱 String email = user.getEmail(); if(email == null || email.isEmpty()){ map.put("email", "登陸郵箱不能為空"); } //檢查郵箱的格式是否正確 if(!email.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$")){ map.put("email", "郵箱格式不正確"); } //檢查驗證碼是否相等 String verifyCode = user.getVerifyCode(); //獲得session中保存的驗證碼 String sessionCode =(String) request.getSession().getAttribute("vCode"); if(!verifyCode.equalsIgnoreCase(sessionCode)){ map.put("verifyCode", "驗證碼不正確"); } return map; } public Map validateLoginParams(User user,HttpServletRequest request){ Map<String, String> map = new HashedMap(); //校驗用戶名 String loginName = user.getLoginname(); if(loginName == null || loginName.isEmpty()){ map.put("loginname", "用戶名不能為空"); } if(loginName.length() < 3 || loginName.length() > 20){ map.put("loginname", "用戶名長度應該在3到20之間"); } //檢查驗證碼是否相等 String verifyCode = user.getVerifyCode(); //獲得session中保存的驗證碼 String sessionCode =(String) request.getSession().getAttribute("vCode"); if(!verifyCode.equalsIgnoreCase(sessionCode)){ map.put("verifyCode", "驗證碼不正確"); } return map; } /* * 當用戶修改密碼的時候會調用該方法 * */ public String updatePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*業務操作的流程 * 1、將請求的參數封裝成javaBean對象 * 2、獲得當前登錄用戶的uuid * 3、利用uuid和原始的密碼去查找用戶是否存在 * 3、利用uuid去修改新的密碼 * * */ System.out.println("updatePassword is called"); User formUser = CommonUtils.toBean(request.getParameterMap(), User.class); //如果用戶登錄成功了,會在session中保存該用戶 User loginUser = (User) request.getSession().getAttribute("sessionUser"); if(loginUser == null){//說明當前用戶沒有登錄,到pwd.jsp顯示異常信息 request.setAttribute("msg", "用戶沒有登錄,請先登錄在修改用戶密碼"); return "f:/jsps/user/login.jsp"; } try { service.updateUserPassword(loginUser.getUid(), loginUser.getLoginpass(), formUser.getNewpass()); //說明修改密碼成功 request.setAttribute("code", "success"); request.setAttribute("msg", "用戶修改密碼成功,請重新登錄"); return "f:/jsps/msg.jsp"; } catch (Exception e) { //修改密碼失敗 request.setAttribute("msg",e.getMessage()); return "f:/jsps/user/pwd.jsp"; } } }
因為登陸是到UserServlet的updatePassword中進行操作,所以需要在pwd.jsp頁面配置
pwd.jsp的代碼:
<%@ 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>pwd.jsp</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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <link rel="stylesheet" type="text/css" href="<c:url value='/css/css.css'/>"> <link rel="stylesheet" type="text/css" href="<c:url value='/jsps/css/user/pwd.css'/>"> <script type="text/javascript" src="<c:url value='/jquery/jquery-1.5.1.js'/>"></script> <%--引入pwd.js文件 --%> <script type="text/javascript" src="<c:url value='/jsps/js/user/pwd.js'/>"></script> <script src="<c:url value='/js/common.js'/>"></script> </head> <body> <div class="div0"> <span>修改密碼</span> </div> <div class="div1"> <form action="<c:url value='/UserServlet'/>" method="post" target="_top"> <input type="hidden" name="method" value="updatePassword"/> <table> <tr> <td><label class="error">${msg }</label></td> <td colspan="2"> </td> </tr> <tr> <td align="right">原密碼:</td> <td><input class="input" type="password" name="loginpass" id="loginpass" value=""/></td> <td><label id="loginpassError" class="error"></label></td> </tr> <tr> <td align="right">新密碼:</td> <td><input class="input" type="password" name="newpass" id="newpass" value=""/></td> <td><label id="newpassError" class="error"></label></td> </tr> <tr> <td align="right">確認密碼:</td> <td><input class="input" type="password" name="reloginpass" id="reloginpass" value=""/></td> <td><label id="reloginpassError" class="error"></label></td> </tr> <tr> <td align="right"></td> <td> <img id="vCode" src="/VerifyCodeServlet" border="1"/> <a href="javascript:changeVerifyCode();">看不清,換一張</a> </td> </tr> <tr> <td align="right">驗證碼:</td> <td> <input class="input" type="text" name="verifyCode" id="verifyCode" value=""/> </td> <td><label id="verifyCodeError" class="error"></label></td> </tr> <tr> <td align="right"></td> <td><input id="submit" type="submit" value="修改密碼"/></td> </tr> </table> </form> </div> </body> </html>