原生js进行ajax验证账户是否存在

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>注册</title>
 8 <script type="text/javascript" src="/preparedTest/js/jquery.js"></script>
 9 </head>
10 <body>
11 <form action="register" method="post"   enctype="multipart/form-data" >
12         <p>
13         <span>学号:</span>
14         <input type="text" name="id" id="number"/>
15         </p>
16         <p>
17         <span>姓名:</span>
18         <input type="text" name="name"/>
19         </p>
20         <p>
21         <span>密码:</span>
22         <input type="password" name="password"/>
23         </p>
24         <p>
25         <span>确认密码:</span>
26         <input type="password" name="repassword"/>
27         </p>
28         <p>
29         <span>性别:</span>
30         <input type="radio" name="sex" value="男"/>31         <input type="radio" name="sex" value="女"/>32         </p>
33         <p>
34         <span>专业:</span>
35         <input type="text" name="specialty"/>
36         </p>
37         <p>
38             <span>上传头像:</span>
39             <input type="file" name="imgurl">
40         </p>
41         <p>
42         <input type="submit" value="注册"/>
43         </p>
44     </form>
45 </body>
46     <script type="text/javascript">
47     
48     var oId = document.getElementById('number');
49     oId.onblur = function(){
50         var xhr = new XMLHttpRequest();
51         xhr.open('get','checkId?id='+oId.value,true);
52         xhr.send();
53         xhr.onreadystatechange = function() {
54                 if ( xhr.status == 200 ) {
55                   var res = xhr.responseText 
56                   if(res === 'error'){
57                         alert("该账户已经存在");
58                     } else if(res === 'empty'){
59                         alert("账户不能为空");
60                     }
61                 } 
62             }
63     }
64 
65     
66     /*     $('input[name="id"]').blur(function(){
67             $.ajax({
68                 type:'post',
69                 url:'checkId',
70                 data:{'id':$('input[name="id"]').val()}
71                 success:function(res){
72                     if(res === 'error'){
73                         alert("该账户已经存在");
74                     } else if(res === 'empty'){
75                         alert("账户不能为空");
76                     }
77                 }
78             });
79         }) */
80     </script>
81 </html>
 1 package servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.mysql.jdbc.StringUtils;
12 
13 import bean.Student;
14 import dao.StudentDao;
15 
16 @WebServlet("/checkId")
17 public class CheckIdServlet extends HttpServlet {
18     private StudentDao dao;
19     @Override
20     public void init() throws ServletException {
21         dao = new StudentDao();
22         super.init();
23     }
24     
25     @Override
26     protected void service(HttpServletRequest req, HttpServletResponse resp) 
27             throws ServletException, IOException {
28         if(StringUtils.isNullOrEmpty(req.getParameter("id"))) {
29             resp.getWriter().write("empty");
30         }else {
31             long id = Long.valueOf(req.getParameter("id"));
32             
33             Student student = dao.getStudentById(id);
34             System.out.println(student);
35             if(student != null) {
36                 resp.getWriter().write("error");
37             }else {
38                 resp.getWriter().write("ok");
39             }
40         }
41         
42     }
43     
44 }
package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import bean.Grade;
import bean.Student;

public class StudentDao {
    private static final String username = "root";
    private static final String password = "123456";
    private static final String url = "jdbc:mysql://localhost:3306/kaoshi?useUnicode=true&characterEncoding=utf-8";
    public Connection connect() {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return con;
    }
    public void disConnect(Connection con, Statement st, ResultSet rs) {
        if(con != null) {
            try {
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if(st != null) {
            try {
                st.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if(rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
        
    public int insertStudent(Student student) {
        Connection con = null;
        PreparedStatement pstm = null;
        try {
            con = this.connect();
            String sql = "insert into student(id, name, pwd, sex, specialty, imgurl) values(?, ?, ?, ?, ?, ?)";
            pstm = con.prepareStatement(sql);
            pstm.setLong(1, student.getId());
            pstm.setString(2, student.getName());
            pstm.setString(3, student.getPwd());
            pstm.setString(4, student.getSex());
            pstm.setString(5, student.getSpecialty());
            pstm.setString(6, student.getImgurl());
            int i = pstm.executeUpdate();
            return i;
        } catch (Exception e) {
            this.disConnect(con, pstm, null);
            e.printStackTrace();
        }
        return 0;
    }
    
    public Student getStudentById(long id) {
        Connection con = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            con = this.connect();
            String sql = "select * from student where id=?";
            pstm = con.prepareStatement(sql);
            pstm.setLong(1, id);
            rs = pstm.executeQuery();
            Student student = null;
            while(rs.next()) {
                student = new Student(rs.getLong(1), rs.getString(2), rs.getString(3),
                        rs.getString(4),rs.getString(5), rs.getString(6));
            }
            return student;
        } catch (Exception e) {
            this.disConnect(con, pstm, rs);
            e.printStackTrace();
        }
        return null;
    }
    public List<Grade> getGradeById(long id){
        Connection con = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<Grade> list = new ArrayList<>();
        try {
            con = this.connect();
            String sql = "select * from grade where id=?";
            pstm = con.prepareStatement(sql);
            pstm.setLong(1, id);
            rs = pstm.executeQuery();
            
            while(rs.next()) {
                Grade grade = new Grade(rs.getString(1), rs.getString(2),
                        rs.getString(3),rs.getLong(4));
                list.add(grade);
            }
            return list;
        } catch (Exception e) {
            this.disConnect(con, pstm, rs);
            e.printStackTrace();
        }
        return null;
    }
}
原文地址:https://www.cnblogs.com/seekknowledge/p/12159230.html