实例:Ajax+Servlet+JDBC查询用户名

2017-11-05  本文已影响0人  lhdoeo

Ajax简单来说就是通过js来向后端发送请求,相比使用表单通过跳转来实现发送请求,Ajax可以做到页面不刷新并获取后端响应。

HTML代码:
并没有使用表单发送

<body>
    <form id="interface">
        <p>注册</p>
        <div id="input1">
            <p>用户名</p><input type="text" name="user_name" id="user_name"/>
            <div id="state_box">
                <div id="user_name_state">
                    <div class="state_icon" id="user_name_state_icon"></div>
                    <p></p>
                </div>
            </div>
        </div>
        <div id="input2">
            <p>密码</p><input type="text" name="user_password" id="user_password"/>
            <div id="user_password_state">
              <div class="state_icon" id="user_password_state_icon"></div>
              <p></p>
            </div>
        </div>
        <input type="button" value="注册" id="enroll"/>
    </form>
</body>

JS代码:
简单使用了JSON

window.onload=function(){
    var xhr = new XMLHttpRequest();
    document.getElementById("enroll").addEventListener("click",function(){
        uns.removeAttribute('class');
        xhr.open("POST","/Ajax/check",true);
        xhr.setRequestHeader("Content-Type","application/json");
        var json = JSON.stringify({
            "user_name":document.getElementById("user_name").value.toString(),
            "user_password":document.getElementById("user_password").value.toString()               
        })
        xhr.send(json);
    })
    var uns = document.getElementById("user_name_state");
    var unsi = document.getElementById("user_name_state_icon");
    xhr.addEventListener("readystatechange",function(){
        if(xhr.readyState==4&&xhr.status==200){
            uns.style.opacity=1;
            uns.setAttribute('class',"shake");
            switch(xhr.responseText.toString()){
                case "user_name too long":
                    unsi.style.cssText="background: url(error.png) no-repeat;background-size: contain;background-position: center;";
                    unsi.nextSibling.nextSibling.innerText="用户名过长";break;
                case "user_name is empty":
                    unsi.style.cssText="background: url(error.png) no-repeat;background-size: contain;background-position: center;";
                    unsi.nextSibling.nextSibling.innerText="你要做甚?";break;
                case "user_name is available":
                    unsi.style.cssText="background: url(correct.png) no-repeat;background-size: contain;background-position: center;";
                    uns.lastChild.previousSibling.innerText="";break;
                case "user_name has been occupied":
                    unsi.style.cssText="background: url(error.png) no-repeat;background-size: contain;background-position: center;";
                    unsi.nextSibling.nextSibling.innerText="用户名已被占用";break;
            }
        }
    })
}

JAVA代码:
调用JDBC

@WebServlet("/LhdServlet")
public class LhdServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LhdServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        System.out.println("收到请求");
        System.out.println(request.getContentType());
        request.setCharacterEncoding("utf-8");
        //读取JSON数据
        BufferedReader br = new BufferedReader(request.getReader());
        StringBuffer json = new StringBuffer();
        String line = null;
        while((line=br.readLine())!=null) {
            json.append(line);
        }
        String info = json.toString();
        JsonParser parser = new JsonParser();
        JsonObject object = (JsonObject) parser.parse(info);
        String name = object.get("user_name").getAsString();
        String password = object.get("user_password").getAsString();
        System.out.println("name:"+name+'\n'+"password:"+password);
        //获取用户名称长度(单位为字节),UTF-8下一个汉字占3个字节
        int user_name_length = object.get("user_name").getAsString().length();
        if(user_name_length>21) {
            response.getWriter().write("user_name too long");
        }
        else {
            if(user_name_length == 0) {
                response.getWriter().write("user_name is empty");
            }
            else{
                System.out.println("开始核对用户名");
                //注册MySQL数据库服务器的驱动
                try {
                    DriverManager.registerDriver(new Driver());
                    //获取与MySQL数据库服务器的连接
                    //jdbc:主协议
                    //mysql:子协议
                    //127.0.0.1:数据库服务器是位于哪台PC上,可以用ip/域名表示
                    //3306 数据库默认端口
                    //users:表示MySQL数据库服务器上具体的数据库
                    String url = "jdbc:mysql://127.0.0.1:3306/users";
                    Connection conn = (Connection) DriverManager.getConnection(url, "root", "lhd123");
                    System.out.println(conn!=null?"连接成功":"连接失败");
                    //创建封装SQL语句的对象
                    Statement stmt = (Statement) conn.createStatement();
                    //处理结果集
                    String sql = "select username from information where username='"+name+"'";//ctrl+shift+x快速大写
                    ResultSet rs = stmt.executeQuery(sql);
                    if(rs.next()) {
                        conn.close();
                        System.out.println("用户名重复");
                        response.getWriter().write("user_name has been occupied");
                    }
                    else {
                        conn.close();
                        System.out.println("用户名可用");
                        response.getWriter().write("user_name is available");
                    }
                }
                catch(SQLException e){
                    e.printStackTrace();
                }
            }
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

效果:

上一篇下一篇

猜你喜欢

热点阅读