ajax与servlet--验证用户名是否存在

来源:互联网 发布:印尼排华 知乎 中国 编辑:程序博客网 时间:2024/05/21 08:54

            验证用户名是否存在--使用jQuery

一、数据库mysql

              数据库中已经存在用户名。


二、html页面     

<body>    <h1>用户登录</h1>    <hr>    <form name="regForm" action="dologin.jsp" method="post">        <table>            <tr>                <td>username</td>                <td><input id="Name"  type="text" name="username"/><span id="msg">请输入昵称</span></td>            </tr>            <tr>                <td>password</td>                <td><input type="password" name="password"/></td>            </tr>            <tr>                <td colspan="2"><input type="submit" value="submit"/></td>            </tr>        </table>        <a href="/myblog/register.jsp">没有账号?立即注册。</a>      </form></body>


三、jQuery代码--ajax

当表单里的用户名失去焦点时,就会触发该ajax,与后端Ajax类交互。

  <script type="text/javascript" src="${path}js/jquery-3.1.1.js"></script>  <script type="text/javascript">   $(document).ready(function(){   $("#Name").blur(function(){ var user = {username:$("#Name").val()};  $.ajax(   {url:"http://localhost:8080/myblog/ajax",   data:user,   async:true,   type:"POST",   dataType:"html",   success:function(result){   $("#msg").html(result); }           });                });   })    </script>


四、后台类Ajax.java

该类中引用了DB类,方便创造数据库实例。该类与数据库交互,并返回数据到前端。

public class Ajax extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {             response.setContentType("text/html");        response.setCharacterEncoding("utf-8");String name = request.getParameter("username");//连接数据库try{//创建数据库的连接Connection conn = DB.getConn();//sql语句String sql ="SELECT * FROM admin where username= ? ";PreparedStatement pstm = conn.prepareStatement(sql);pstm.setString(1, name); ResultSet rs = pstm.executeQuery(); if(rs.next()){ response.getWriter().print("您的用户名已经注册");}else{response.getWriter().print("验证成功");}  }catch(Exception e){e.printStackTrace();}}}

五、在Ajax.java中使用了DB类

创建数据库实例。


public class DB {private static Connection conn =null;private DB(){}public static Connection getConn(){if (conn != null) {return conn;}try{ Class.forName("com.mysql.jdbc.Driver");    String url = "jdbc:mysql://localhost/webuser?useUnicode=true&characterEncoding=utf-8&useSSL=false";conn= DriverManager.getConnection(url,"root", "17911");return conn;}catch(Exception e){e.printStackTrace();return null;}}}


六、运行效果


未输入时:

jsh为已注册用户:


新用户:



七、展望

     
上面废话不多,直接写了html、js、servlet的代码,写javaweb学生信息管理系统应该会用到。

下次应该就是学生信息管理系统的源代码了。