您现在的位置: 爱51代码网 >> 范文 >> 文章正文
Ajax异步调用后台 实现简单的登录错误提示的实例

Ajax异步调用后台 实现简单的登录错误提示的实例

框架是SSH,其中Action是DispatchAction;
SSH + JSP + MYSQL
Ajax实现页面不刷新 并且把“用户名不正确”、“密码输入有误”这样的提示显示在登录框的下面

<script type="text/javascript">              /*提交验证,异步传输*/              $(document).ready(function(){                  $("form").submit(function (){                   if ($("#name").val() == '' || $("#password").val() == ''){                        alert("帐号和密码不能为空!");                       return false;                        }else{                                     $.ajax({                                              url: 'LoginServlet',       //处理测试页面,注意返回内容,成功返回OK                                              dataType: 'text',                                              data: $("form").serialize(),                                              success: function (msg) {                                                  if (msg == "ok"){                                 window.location.href = "IndexServlet";                             }else{                                                           alert("帐号或密码不正确,请您重新输入!");                                                           return;                                                       }                                               }                                       });                                }                         return false;                         ////////////////要阻止表单提交                      });             });                           </script>

public void doPost(HttpServletRequest request, HttpServletResponse response)             throws ServletException, IOException {         request.setCharacterEncoding("UTF-8");         response.setCharacterEncoding("UTF-8");                   PrintWriter out = response.getWriter();         //获取帐号密码         String name = request.getParameter("name");         String password = request.getParameter("password");         String remerber = request.getParameter("remerber_password");                             UsersService usersService = Factory.getUsersService();         //获取验证后的用户实体类         Users users = usersService.checkLogin(name, password);                   if(users.getId() != 0){             //把用户信息放入session中             request.getSession().setAttribute("users", users);                           if("on".equals(remerber)){                   Cookie cookieuser = new Cookie("user",name+"-"+password);                    //设定有效时间  以秒(s)为单位  保存1个星期                   cookieuser.setMaxAge(60*60*24*7);                   response.addCookie(cookieuser);             }                           //跳到IndexServlet中             //response.sendRedirect("IndexServlet?name="+name);             out.print("ok");         }else{             //response.sendRedirect("fail.jsp");             out.print("error");         }         out.flush();         out.close();     }

先是test.jsp

JavaScript code?<script language="JavaScript"> //创建XmlHttpRequest对象。 var xmlHttp; var path = '<%=basePath%>'; //这是获得上下文路径 function creatXMLHttp(){     if(window.XmlHttpRequest){         xmlHttp=new XmlHttpRequest();     }else{         //IE         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");     } }   function checkUserID(userid){     creatXMLHttp();//创建出XMLHttpRequest对象     xmlHttp.open("post",path + "login.do?operation=test", true);//这个路径test不要加引号     xmlHttp.onreadystatechange=checkuseridCallBack;     xmlHttp.send(null); }   function checkuseridCallBack(){     if(xmlHttp.readystate==4){         if(xmlHttp.status==200){             var text=xmlHttp.responseText;             if(text=='true'){                 document.getElementById("mes").innerHTML="用户ID已经存在,无法使用!";             } else {                 document.getElementById("mes").innerHTML="用户名可以使用!";             }         }     } }


然后是HTML

XML/HTML code?<form action="" method="post" >          用户名:<input type="text" name="userid" onblur="checkUserID(this.value)"/>          <span id="mes"><font color="blue">自动验证用户ID</font></span><br/>           姓  名:<input type="text" name="name"/><br/>            密  码:<input type="text" name="password"/> <br/>          <input type="submit" value="提交"/>          <input type="reset" value="重置"/> </form>

 

再然后是action 是一个DispatchAction哦

Java code?public class LoginAction extends DispatchAction {                     public ActionForward test(ActionMapping mapping, ActionForm form,             HttpServletRequest request, HttpServletResponse response) {                   try {             request.setCharacterEncoding("UTF-8");             response.setCharacterEncoding("UTF-8");         } catch (UnsupportedEncodingException e) {             e.printStackTrace();         }                   try {             response.getWriter().print("true");//这个print不要println因为println会多返回一个换行,这样和javascript中的true就不能相等了         } catch (IOException e) {             e.printStackTrace();         }         return null;     } }


最后是struts的配置文件

Plain Text code?//其他的都不重要 parameter="operation"是DispatchAction中从传递的参数中 寻找执行的方法 <action path="/login" type="com.mulan.struts.action.LoginAction" parameter="operation">       <set-property property="cancellable" value="true" />       <forward name="index" path="/index.jsp" />       <forward name="register" path="/register.jsp"/>       <forward name="test" path="/test/test.jsp"/> </action>

  • 上一篇文章:

  • 下一篇文章: 没有了
  • 最新文章 热点文章 相关文章
    android手机无法与eclipse或电脑
    C/C++洗牌算法源代码
    servlet技术实现用户名唯一的验证
    E-business suite system servic
    ZOJ 3700 Ever Dream 文章中单词
    TortoiseGit和msysGit安装及使用
    asp中有一段javascipt的网页鼠标
    sharepoint 2010 获取用户信息Us
    设计包含max函数的队列
    随机从数组中取出指定的不重复的
    ZOJ 3700 Ever Dream 文章中单词
    TortoiseGit和msysGit安装及使用
    sharepoint 2010 获取用户信息Us
    mysql主从同步延迟方案解决的学习
    生日旅行总结
    中小板生日快乐随感
    送生日快乐桑葚乳酪小蛋糕
    写给女儿的生日快乐
    总分公司财务核算
    恢复使用繁体字可行性研究报告
    定时将SQL SERVER2000中一个
    Exception in thread "Timer
    Exception sending context 
    Eclipse下启动tomcat报错:/
    Java通过IP地址获取用户所在
    struts2+hibernate 实现B2C电
    android编译时出现'Unab
    Android 仿 WP7 布局
    windows下搭建SVN服务器及配
    javascript中级联下拉列表
     



    设为首页 | 加入收藏 | 网站地图 | 友情链接 |