创建UserDao:
public User getUserByUsername(String username){
User user = null;
String sql = "select * from tb_user where u_name = ?";
try{
super.getConnection();
pstm = con.prepareStatement(sql);
pstm.setString(1, username);
rs = pstm.executeQuery();
if(rs.next()){
user = new User();
user.setU_id(rs.getInt("u_id"));
user.setU_name(rs.getString("u_name"));
user.setU_password(rs.getString("password"));
}
}catch (Exception e) {
System.out.println("-----getUserByUsername() was error!!!-------");
}finally{
super.closeAll();
}
return user;
}
页面代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ajax检测用户是否被占用</title>
<script type="text/javascript">
function validateUser(){
var username=$.trim($("#name").val());
if(!username){
alert("用户名不能为空!");
return null;
}
$.ajax({
url:'validateServlet',
type:'POST',
data:$("#registerForm").serialize(),
dataType:'json',
success:function(data){
if(data.success==false){
alert(data.msg);
return;
}else{
alert(data.msg);
return;
}
}
});
}
</script>
</head>
<body>
<form id="registerForm" name="registerForm">
<table>
<tr>
<td>用户名:</td>
<td>
<input type="text" name="name" id="name" οnblur="validateUser()"/>
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name="pwd" id="pwd" />
</td>
</tr>
<tr>
<td>确认密码:</td>
<td>
<input type="password" name="pwd1" id="pwd1" />
</td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" name="sex" id="m" value="m"/>男
<input type="radio" name="sex" id="f" value="f"/>女
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="注 册"/>
</td>
</tr>
</table>
</form>
</body>
</html>
servlet 代码
String userName = request.getParameter("name");
UserDao userDao = new UserDao();
User user = userDao.getUserByUsername(userName);
if(user != null){
JSONKit.outJSONInfo("{success:false,msg:'用户名重复!'}", response);
}else{
JSONKit.outJSONInfo("{success:true,msg:'此用户名可以注册!'}", response);
}
如果需要还可以到下载完整代码http://download.csdn.net/detail/zhu_nana/4599031