java中如何使用ajax判断用户名是否已注册

1、在webContent 下的reg.jsp文件中引用js文件夹下的jquery和reg.js文件

<script src="js/jquery1.11.3.min.js"></script>
<script src="js/reg.js"></script>

2、在reg.jsp的body中添加表单

<form action="" method="post">
<pre>
用户名:<input type='text' name='userName'><span id="s1"></span>
密码:<input type='password' name='userPassword'>
确认密码:<input type='password' name='repwd'>
<input type='submit' name='sub' value="注册">
</pre>
</form>

3、在reg.js中写jquery和ajax

$(function(){
    $(":text[name='userName']").blur(function(){
        //1、获得用户名
        var userName=$(this).val();
        //2、通过异步传输对象将用户名传到服务器,服务器查询数据库得到结果并返回
        $.get("CheckUnameServlet?userName="+userName,function(data){
            if(data=="1"){
                $("#s1").html("该用户已注册");
            }else{
                $("#s1").html("可以注册");
            }
            
        })
    })
})

4、在CheckUnameServlet中写服务器连接数据库代码,这个servlet放在src下的名为servlet的包下

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
        //禁用缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        
        String userName = request.getParameter("userName");
        String sql="select * from 数据表名 where userName=?";
        List<Object> paramList=new ArrayList<Object>();
        paramList.add(userName);
        DbHelper dbHelper=new DbHelper();
        List<Map<String, Object>> list = dbHelper.executeQuery(sql, paramList);
        if(list!=null && list.size()>0) {
            response.getWriter().print("1");
        }else {
            response.getWriter().print("0");
        }
    }

5、其中引用了禁用缓存代码

response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);

6、其中调用了自己写的工具类:DbHelper.java,放在JavaResources下的util包下

package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.print.attribute.standard.RequestingUserName;

public class DbHelper {
    
    private Connection connection;
    
    private PreparedStatement preparedStatement;
    
    private ResultSet resultSet;
    
    public DbHelper()
    {
        getConnection();
    }
    //与数据库连接
    public void getConnection()
    {
         try {          
              if(connection==null || connection.isClosed())
              {
                //获取db.properties中的数据
                Properties properties=new Properties();
                
                InputStream iStream=this.getClass().getResourceAsStream("/db.properties");
                
                properties.load(iStream);
                
                String driver=properties.getProperty("driver");
                
                String url=properties.getProperty("url");
                
                String uname=properties.getProperty("uname");
                
                String pwd=properties.getProperty("pwd");
                  
                  
                Class.forName(driver);
             
                this.connection= DriverManager.getConnection(url, uname, pwd);
              }
            
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
         
    }   
    
    //实现增删改操作
    public int executeUpdate(String sql,List<Object> paramList)
    {
         getConnection();   
         
         try {
            
             this.preparedStatement=connection.prepareStatement(sql);
            
             //如果在数据库中查询到对应信息,则返回更新
             if(paramList!=null)
             {
                  for(int i=0;i<paramList.size();i++)
                  {
                      this.preparedStatement.setObject(i+1, paramList.get(i));
                  }
             }
             
             return this.preparedStatement.executeUpdate();
             
             
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            close();
        }
         
        return 0;
    }
    
    //执行查询操作
    public List<Map<String, Object>> executeQuery(String sql,List<Object> paramList)
    {
         getConnection();
         
         try {
             this.preparedStatement=connection.prepareStatement(sql);
        
             if(paramList!=null)
             {
                  for(int i=0;i<paramList.size();i++)
                  {
                        this.preparedStatement.setObject(i+1, paramList.get(i));
                  }
             }
             
             this.resultSet= this.preparedStatement.executeQuery();
             
             List<Map<String, Object>> resultList=new ArrayList<Map<String,Object>>();

             ResultSetMetaData resultSetMetaData= this.resultSet.getMetaData();
             
             
             while(resultSet.next())
             {
                 Map<String, Object> map=new HashMap<String,Object>();
                 
                 for(int i=1;i<=resultSetMetaData.getColumnCount();i++)
                 {
                     
                       String columnname=  resultSetMetaData.getColumnName(i);
                      
                       Object columnvalue=resultSet.getObject(columnname);
                       
                       map.put(columnname, columnvalue);
                       
                 }
                 
                 resultList.add(map);
                 
             }
             
             return resultList;
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            close();
        }
         
        return null;
         
    }
    
    //执行关闭操作
    public void close()
    {
         if(resultSet!=null)
            try {
                resultSet.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         
         if(preparedStatement!=null)
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         
         if(connection!=null)
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    

}

7、其中使用了db.properties文件,文件放在src文件夹下

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名?characterEncoding=utf-8
uname=数据库用户名
pwd=数据库密码
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容