註冊登陸界面尤其常見,個人界面尤其難看,勉爲其難的寫吧,前端不熟就是這樣。。。css
這個案例運用到了:html
1.Jsp動態頁面--->動態頁面前端
2.Servlet邏輯判斷後臺---->實現界面與數據庫/業務的鏈接,簡而言之,起承轉合。PS:後臺響應Ajax後往前端回數據時,需按照前端規定的數據類型進行Write(),才能夠在success中獲取,data.xxxx。java
3.MYSQL數據庫----->持久化數據jquery
4.JDBC----->Java DataBase Connectivity,Java數據庫鏈接ajax
5.C3P0數據源鏈接池------>開源的JDBC鏈接池spring
6.JQuery------>輕量級 JavaScript 庫數據庫
7.DButils工具類----->簡化數據庫CRUD操做apache
8.網易雲信------>第三方驗證碼發送平臺,因爲我操做太頻繁被限制了......,內有Java接入示例(http://dev.netease.im/docs/product/%E7%9F%AD%E4%BF%A1/%E7%9F%AD%E4%BF%A1%E6%8E%A5%E5%85%A5%E7%A4%BA%E4%BE%8B),有二十條免費的能夠測試Java程序發送手機驗證碼(用完就沒了),須要注意的是添加依賴後,還可能報錯,需再添加commons.logging.jarjson
9.javax.mail.jar---->簡單郵件發送依賴jar,發送郵件首先須要有一個郵箱帳號和密碼,以網易163郵箱爲例,郵箱帳號必需要開啓 SMTP 服務,在瀏覽器網頁登陸郵箱後通常在郵箱的「設置」選項中能夠開啓,並記下郵箱的 SMTP 服務器地址
看起來有點麻煩,畫個註冊部分的邏輯:
頁面的CSS是真的沒想象力去寫,ε=(´ο`*)))界面難看。。。。。。。。。
工程MVC(model、view、control)結構:
我的感受就是將原來什麼都混在一塊兒,像疊衣服同樣,衣服是衣服,褲子是褲子的放起來,這樣找起來比較方便,那麼相應的格局開始就要佈置好,會稍微麻煩點,但總體寫法不會由於這個改變。
依賴:
註冊部分代碼(CSS就不上了,這麼渣的樣式...感受要被鄙視了0.0.):
Register,jsp---------->頁面顯示
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>註冊</title> <link rel="stylesheet" href="css/Register.css"> <script src="jquery/jquery-1.11.1.js"></script> <script> $(function () { //用戶註冊和用戶登陸切換 $("#li_register").click(function () { $("#register").show(); $("#login").hide(); }) $("#li_login").click(function () { $("#login").show(); $("#register").hide(); }) //給發送按鈕綁定點擊事件:獲取電話號碼檢驗是否爲電話號碼,ajax到後臺 $("#bt_send").click(function () { var phone=$("#r_telephone").val(); var pattern=/^1(3|4|5|7|8)\d{9}$/; if(!(pattern.test(phone))){ alert("請輸入正確的電話號碼"); return; } //進行ajax數據交互,此處切記button可能會致使Ajax請求失敗,改成input便可,大坑啊.... $.ajax({ url:"SendPhoneVerifyCode", type:"get", data:{phone:phone}, dataType:"json", success:function (data) { alert(data.message); }, error:function (err) { alert("發送失敗") console.log(err); } }); }) }) </script> </head> <body> <div id="content"> <div id="tip"> <ul> <li id="li_register">用戶註冊</li> <p>/</p> <li id="li_login">用戶登陸</li> </ul> </div> <div id="register"> <form action="UserRegisterServlet" method="post"> 用戶名: <input type="text" name="r_username" id="r_username"><br> 密 碼: <input type="password" name="r_password" id="r_password"><br> 電話號碼:<input type="text" name="r_telephone" id="r_telephone"><br> 驗證碼:<input type="text" name="phoneVerifyCode" id="phoneVerifyCode"><input type="button" id="bt_send" value="點擊發送"> <br> <input type="submit" value="點擊註冊,貪玩藍月"><br> <span id="r_messageShow">${sessionScope.messageShow}</span> </form> </div> //登陸還沒寫......... <div id="login"> <form action=""> 用戶名: <input type="text" name="l_username" id="l_username"><br> 密 碼:<input type="password" name="l_password" id="l_password"><br> <input type="submit" value="點擊登陸,渣渣輝"><br> <span id="l_messageShow"></span> </form> </div> </div> </body> </html>
SendPhoneVerifyCode----->ajax發送數據的後端servlet,接收前端發來的電話號碼,並執行發送驗證碼的動做
public class SendPhoneVerifyCode extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); //獲取電話號碼 String phone = request.getParameter("phone"); //給當前號碼發送驗證碼,返回驗證碼存在session裏,就是這裏把我限制了,雲信都登不上了,不過不影響使用 String code = new PhoneVerifyCode(phone).sendCode(); request.getSession().setAttribute("phoneCode",code);//session是存在於服務器上滴,cookie是在客戶端滴 //將json數據返回前端,提示用戶 response.getWriter().write("{\"message\":\"信息已發送\"}"); } }
PhoneVerifyCode--->網易雲信的提示中有代碼,記得在copy一下它的CheckSumBuilder類,會用到,還要添加兩個JAR包httpcore-4.4.3.jar和httpclient-4.5.1.jar,若是報錯中有logging等字眼,再添加com.springsource.org.apache.commons.logging-1.1.1.jar
public class PhoneVerifyCode { //發送驗證碼的請求路徑URL private static final String SERVER_URL="https://api.netease.im/sms/sendcode.action"; //網易雲信分配的帳號,請替換你在管理後臺應用下申請的Appkey private static final String APP_KEY="d39afb7b5b9ece021935351e74f75d98"; //網易雲信分配的密鑰,請替換你在管理後臺應用下申請的appSecret private static final String APP_SECRET="543d6e574be7"; //隨機數 private static final String NONCE="123456"; //短信模板ID private static final String TEMPLATEID="4062279"; //手機號 private static String MOBILE=""; //驗證碼長度,範圍4~10,默認爲4 private static final String CODELEN="6"; public PhoneVerifyCode(String MOBILE){ this.MOBILE=MOBILE; } public String sendCode(){ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(SERVER_URL); String curTime = String.valueOf((new Date()).getTime() / 1000L); /* * 參考計算CheckSum的java代碼,在上述文檔的參數列表中,有CheckSum的計算文檔示例 */ String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime); // 設置請求的header httpPost.addHeader("AppKey", APP_KEY); httpPost.addHeader("Nonce", NONCE); httpPost.addHeader("CurTime", curTime); httpPost.addHeader("CheckSum", checkSum); httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); // 設置請求的的參數,requestBody參數 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); /* * 1.若是是模板短信,請注意參數mobile是有s的,詳細參數配置請參考「發送模板短信文檔」 * 2.參數格式是jsonArray的格式,例如 "['13888888888','13666666666']" * 3.params是根據你模板裏面有幾個參數,那裏面的參數也是jsonArray格式 */ nvps.add(new BasicNameValuePair("templateid", TEMPLATEID)); nvps.add(new BasicNameValuePair("mobile", MOBILE)); nvps.add(new BasicNameValuePair("codeLen", CODELEN)); try { httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // 執行請求 HttpResponse response = null; try { response = httpClient.execute(httpPost); } catch (IOException e) { e.printStackTrace(); } /* * 1.打印執行結果,打印結果通常會200、31五、40三、40四、41三、41四、500 * 2.具體的code有問題的能夠參考官網的Code狀態表 */ String respJSON= null; try { respJSON = EntityUtils.toString(response.getEntity(), "utf-8"); System.out.println(respJSON); } catch (IOException e) { e.printStackTrace(); } Gson gson=new Gson(); CodeEntity entity = gson.fromJson(respJSON, CodeEntity.class); String ss=entity.getObj(); //由於把我限制了,致使給個人驗證碼格式不對,截取前面的便是驗證碼,正經常使用戶直接getobj()便是驗證碼,沒辦法被限制了... System.out.println(ss.substring(0,7)); return ss.substring(0,7); } }
UserRegisterServlet---->用戶註冊判斷用戶填寫的數據是否能夠註冊的servlet
public class UserRegisterServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("r_username"); String password = request.getParameter("r_password"); String telephone = request.getParameter("r_telephone"); String phoneVerifyCode = request.getParameter("phoneVerifyCode"); User user=new User(username, MD5Util.md5(password),telephone); //開始註冊業務 UserRegister userRegister=new Dao.UserRegister(); if(userRegister.isRepeatUsername(username)){ request.getSession().setAttribute("messageShow","用戶名重複"); response.sendRedirect("Register.jsp"); return; } if(!userRegister.isRightCode(phoneVerifyCode, (String) request.getSession().getAttribute("phoneCode"))){ request.getSession().setAttribute("messageShow","驗證碼錯誤"); response.sendRedirect("Register.jsp"); return; } userRegister.insertUser(user); request.getSession().setAttribute("username",username); request.getRequestDispatcher("RegisterSuccess.jsp").forward(request,response); } }
UserRegister--->實現業務層的接口,對數據庫進行CRUD操做的類
public class UserRegister implements Service.UserRegister{ private DataSource dataSource=new ComboPooledDataSource(); private QueryRunner qr=new QueryRunner(dataSource); @Override public boolean isRightCode(String code, String rightCode) { return code.equalsIgnoreCase(rightCode); } @Override public boolean isRepeatUsername(String username) { User user=null; try { user = qr.query("select * from user where username=?", new BeanHandler<>(User.class), username); } catch (SQLException e) { e.printStackTrace(); } return user!=null; } @Override public void insertUser(User user) { try { qr.update("insert into user(username,password,telephone) values (?,?,?)",user.getUsername(),user.getPassword(),user.getTelephone()); } catch (SQLException e) { e.printStackTrace(); } } }
以上爲註冊模塊主要的代碼,剩下的要麼是實體類(User類用來封裝用戶輸入的信息、CodeEntity類用來將手機驗證碼返回的jsonArray轉爲該對象),要麼是工具類(MD5加密密碼),要麼就是業務層定義的接口(用戶註冊的功能設定)。
差很少就這樣了,就不放上來了,這麼多也不必定看的完..........代碼臃腫,得治。。。註冊短信驗證碼到這裏就實現了,剩下郵件驗證激活和登陸......先放着。
收到的短信能夠本身設置模板,可是要審覈,不要刷的太頻繁,否則o( ̄ヘ ̄o#)---------->{"code":416,"msg":"mobile limit","obj":"4322605||+86-xxxxxxxxx"},mobile limit,電話號碼就xxxxx了。
註冊成功後進入,郵箱激活界面,用戶名可在註冊的Sevlet中存session,在這個頁面經過el獲取-----.>
2018.02.02 記