JavaWeb網上圖書商城完整項目--day02-12.激活功能各層實現
阿新 • • 發佈:2017-05-13
find java writer 之間 and service() 配置文件 private pop
1、我們來看程序的代碼
數據庫層:
1、通過激活碼查找到對應的用戶
2、設置用戶的激活狀態
2、業務層
1、通過數據庫接口通過驗證碼得到對應的用戶
2、判斷當用戶是否為空,如果沒有通過激活碼查找到對應的用戶,說明用戶點擊郵箱上傳的激活碼是無效的,這個時候說明激活失敗,拋出一個業務失敗異常,說明激活碼無效
3、如果用戶不為空,並且用戶的激活狀態是沒有激活的,將用戶的激活狀態設置成true
4、如果用戶不為空,但是用戶的激活狀態是已經激活的,拋出一個業務失敗異常,提示用戶無需重復激活
3、servlet就是調用業務層的方法進行激活,對業務層返回的異常進行處理,在界面上提示激活成功還是激活失敗。我們來看程序的代碼
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); } }
我們來看業務層的代碼:
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()); // 不是業務的異常嗎,而是電腦環境系統數據庫的異常,直接退出線程,無法進行業務的操作了 } } }
我們來看servlet的代碼
package com.weiyuan.goods.user.web.servlet; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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 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 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; } }
對應激活這個操作:激活業務的結果就是:
激活成功
激活碼無效
重復激活
三種結果
所以在業務層,如果是激活碼無效和重復激活這兩個業務操作失敗的我們需要通過拋出異常,讓外面的調用者servlet知道業務失敗的原因,然後servlet對異常進行處理,在對應的界面msg.jsp中將業務操作的結果顯示處理。
同時在業務操作的過程中,還存在其他異常導致業務操作失敗,列如數據庫的sql異常,但是這個異常不是業務本身的異常,而是數據庫的異常,這個時候我們不想讓servlet調用者知道,我們就直接在業務層中
throw new RuntimeException(e.getMessage());拋出一個運行時的異常,直接退出程序。這就是
throw new RuntimeException(e.getMessage())和throw new Exception(e.getMessage())的區別。
JavaWeb網上圖書商城完整項目--day02-12.激活功能各層實現