1. 程式人生 > >ajax與servlet--驗證使用者名稱是否存在

ajax與servlet--驗證使用者名稱是否存在


            驗證使用者名稱是否存在--使用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 {

	@Override
	protected 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學生資訊管理系統應該會用到。

下次應該就是學生資訊管理系統的原始碼了。