form表单登录异步ajax校验

来源:互联网 发布:淘宝大众评审 编辑:程序博客网 时间:2024/06/06 01:02

第一步:准备用户登录的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代码

@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");}}}
第三步:webService处理请求

// 查询用户登录@Path("/customerLogin")@GET@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML })public Customer findByTelephoneAndPassword(@QueryParam("telephone") String telephone,@QueryParam("password") String password);

第四步:拼接查询方法

@Overridepublic 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 implementsModelDriven<T> {// 模型驱动protected T model;@Overridepublic 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);}}



原创粉丝点击