form表單登入非同步ajax校驗
阿新 • • 發佈:2018-12-04
第一步:準備使用者登入的html頁面
<!DOCTYPE html> <html> <head> <meta content="application/xhtml+xml;charset=UTF-8" http-equiv="Content-Type"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <title>我的速運-登陸</title> <link rel="stylesheet" type="text/css" href="css/styleloginsign.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.min.css"> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/angular.min.js"></script> <script type="text/javascript" src="js/self/effect.js"></script> <script type="text/javascript" src="js/self/validate.js"></script> <script type="text/javascript"> function loginindex() { if (document.getElementById("telephone").value == '' || document.getElementById("password").value == '') { alert("請輸入使用者名稱和密碼"); } else { var name, pass; name = document.getElementById("telephone").value; pass = document.getElementById("password").value; //alert(name); //alert(pass); $.ajax({ // async: false, type: "POST", url: "customer_login.action", //注意路徑 (後臺登陸驗證的方法) data: { "telephone": name, "password": pass }, // dataType: "text", success: function(data) { alert(data); if (data == "1") { window.location.href = "index.html#/myhome"; } else { alert("使用者名稱或密碼錯誤,登入失敗"); window.location.href = "login.html"; } } }); } } </script> <!--[if IE]> <script type="text/javascript" src="js/html5.js"></script> <script type="text/javascript" src="js/respond.min.js"></script> <![endif]--> </head> <body style="background-color: #f2f2f2;"> <div class="logincontent"> <div class="loginnav"> <nav class="nav navbar-default"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="#"><img src="images/icon/logo.png"></a> <span class="logintitle">使用者登入</span> </div> </div> </nav> </div> <section class="mainlogin" ng-app="validationApp" ng-controller="mainController"> <div class="container"> <div class="col-md-4 col-md-offset-7 loginbox"> <h4>使用者登入</h4> <form class="form-horizontal" action="#" method="post" name="userForm" novalidate> <div class="form-group"> <label class="col-sm-3 control-label">登入方式</label> <div class="col-sm-7"> <label for="r1" class="radio-inline"><input type="radio" value="0" name="article" onclick="show()" checked/>密碼登入</label> <label for="r2" class="radio-inline"><input type="radio" value="1" name="article" onclick="show()" />手機號登入</label> </div> </div> <div id="format1"> <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }"> <label for="inputaccount" class="col-sm-3 control-label">賬號</label> <div class="col-sm-8"> <input type="text" id="telephone" name="telephone" class="form-control" ng-model="user.name" required placeholder="請輸入賬號"> <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">使用者名稱不可為空.</p> </div> </div> <div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }"> <label for="inputpassword" class="col-sm-3 control-label">密碼</label> <div class="col-sm-8"> <input type="password" class="form-control" id="password" name="password" placeholder="請輸入您的密碼" ng-model="user.password" ng-minlength="3" ng-maxlength="8" required> <p ng-show="userForm.password.$error.minlength" class="help-block">使用者名稱太短了!</p> <p ng-show="userForm.password.$error.maxlength" class="help-block">使用者名稱太長了!</p> </div> </div> <div class="form-group" style="margin-bottom: 0;"> <label for="inputvalidate" class="col-sm-3 control-label">驗證碼</label> <div class="col-sm-5"> <input type="password" class="form-control" id="inputaccount" placeholder="請輸入驗證碼"> </div> <div class="col-sm-3"> <img src="images/icon/yanz.png"> </div> </div> <div class="form-group"> <div class="col-sm-offset-4 col-sm-4"> <div class="checkbox"> <input type="checkbox"><span class="size12"> 記住使用者名稱</span> </div> </div> </div> </div> <div id="format2" style="display:none;"> <div class="form-group"> <label for="inputPassword3" class="col-sm-3 control-label">手機號</label> <div class="col-sm-8"> <input type="text" class="form-control" id="inputaccount" placeholder="請輸入手機號/郵箱/使用者名稱"> </div> </div> <div class="form-group"> <label for="inputvalidate" class="col-sm-3 control-label">驗證碼</label> <div class="col-sm-4"> <input type="password" class="form-control" id="inputaccount" placeholder="驗證碼"> </div> <div class="col-sm-3"> <button class="btn btn-default">獲取驗證碼</button> </div> </div> </div> <div class="col-md-offset-3 col-md-8"> <!--<a href="javascript:" class="btn btn-danger">登入</a>--> <!--<input Type="submit" id="submit" value="登入" class="btn btn-danger" onclick="loginindex()" />--> <a type="button" id="btn" class="btn btn-danger" onclick="loginindex()"/>登入</a> </div> <p class="text-right clearfix">還不是我們的會員?<b><a href="signup.html">立即註冊</a></b></p> </form> </div> </div> </section> <footer> <section class="copyright size12"> <div class="container"> <p class="text-center">地址:北京市昌平區建材城西路金燕龍辦公樓一層 郵編:100096 電話:400-618-4000 傳真:010-82935100 </p> <p class="text-center">京ICP備08001421號京公網安備110108007702</p> </div> </section> </footer> </div> <script language="javascript"> function show() { var format1 = document.getElementById("format1"); var format2 = document.getElementById("format2"); if (event.target.value === "0") { format1.style.display = ""; format2.style.display = "none"; } else if (event.target.value === "1") { format1.style.display = "none"; format2.style.display = ""; } } </script> </body> </html>
第二步:處理非同步請求:後臺java程式碼
第三步:webService處理請求@ParentPackage("json-default") @Namespace("/") @Controller @Scope("prototype") public class CustomerAction extends BaseAction<Customer> { @Action(value = "customer_sendSms") public String sendSms() throws Exception { // 手機號儲存在Customer物件 // 生成簡訊驗證碼 String randomCode = RandomStringUtils.randomNumeric(4); // 將簡訊驗證碼儲存到session中 ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode); System.out.println("驗證碼為:" + randomCode); // 編輯簡訊內容 String msg = "尊敬的使用者您好,本次驗證碼為:" + randomCode; // 呼叫sms服務傳送簡訊 // String result = SmsUtils.sendSmsByHTTP(model.getTelephone(), msg); String result = "000/xxx"; if (result.startsWith("000")) { return NONE; } else { throw new RuntimeException("傳送失敗" + result); } } // 屬性驅動接驗證碼 private String checkCode; public void setCheckCode(String checkCode) { this.checkCode = checkCode; } // 校驗驗證碼,儲存資訊到customer @Action(value = "customer_regist", results = { @Result(name = "success", type = "redirect", location = "signup-success.html"), @Result(name = "input", type = "redirect", location = "signup.html") }) public String regist() { // 獲取session中的驗證碼 String checkCodesession = (String) ServletActionContext.getRequest().getSession() .getAttribute(model.getTelephone()); if (checkCodesession == null || !checkCode.equals(checkCodesession)) { // 驗證碼錯誤,跳回註冊頁面 return INPUT; } // 驗證碼正確,儲存資訊 WebClient.create(Constants.CRM_MANAGEMENT_URL + "/crm_management/services/customerService/customer") .type(MediaType.APPLICATION_JSON).post(model); System.out.println("客戶註冊成功..."); return SUCCESS; } // 使用者登入 @Action(value = "customer_login") public void login() throws IOException { // System.out.println(model.getTelephone()); System.out.println(model.getPassword()); Customer customer = WebClient .create(Constants.CRM_MANAGEMENT_URL +"/crm_management/services/customerService/customerLogin?telephone=" + model.getTelephone() + "&password=" + model.getPassword()) .accept(MediaType.APPLICATION_JSON).get(Customer.class); if (customer != null) { ServletActionContext.getResponse().getWriter().write("1"); } } }
// 查詢使用者登入
@Path("/customerLogin")
@GET
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML })
public Customer findByTelephoneAndPassword(@QueryParam("telephone") String telephone,
@QueryParam("password") String password);
第四步:拼接查詢方法
@Override public Customer findByTelephoneAndPassword(String telephone, String password) { return customerRepository.findByTelephoneAndPassword(telephone,password); }
第五步:查詢資料庫
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
public List<Customer> findByFixedAreaIdIsNull();
public List<Customer> findByFixedAreaId(String fixedAreaId);
@Query("update Customer set fixedAreaId = ? where id = ?")
@Modifying // 修改標識
public void updateFixedAreaId(String fixedAreaId, int id);
@Query("from Customer where telephone = ? and password = ?")
public Customer findByTelephoneAndPassword(String telephone, String password);
}
第六步:抽取類
public class Constants {
public static final String BOS_MANAGEMENT_URL = "http://localhost:9001";
public static final String CRM_MANAGEMENT_URL = "http://localhost:9002";
public static final String BOS_FORE_URL = "http://localhost:9003";
}
第七步:action公共類抽取
public abstract class BaseAction<T> extends ActionSupport implements
ModelDriven<T> {
// 模型驅動
protected T model;
@Override
public T getModel() {
return model;
}
// 構造器 完成model例項化
public BaseAction() {
// 構造子類Action物件 ,獲取繼承父型別的泛型
// AreaAction extends BaseAction<Area>
// BaseAction<Area>
Type genericSuperclass = this.getClass().getGenericSuperclass();
// 獲取型別第一個泛型引數
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
Class<T> modelClass = (Class<T>) parameterizedType
.getActualTypeArguments()[0];
try {
model = modelClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
System.out.println("模型構造失敗...");
}
}
// 接收分頁查詢引數
protected int page;
protected int rows;
public void setPage(int page) {
this.page = page;
}
public void setRows(int rows) {
this.rows = rows;
}
// 將分頁查詢結果資料,壓入值棧的方法
protected void pushPageDataToValueStack(Page<T> pageData) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("total", pageData.getTotalElements());
result.put("rows", pageData.getContent());
ActionContext.getContext().getValueStack().push(result);
}
}