js代码
window.onload = function() {
document.getElementById("userName").onblur = function() {
//alert("dfsa");
x = new XMLHttpRequest();
x.open("get", "back/user?methodName=checkUserName&name="
+ this.value, true);
x.send();
x.onreadystatechange = function() {
if (x.readyState == 4) {
if (x.status == 200) {
document.getElementById("message").innerHTML = x.responseText;
} else {
alert("服务器故障");
}
}
}
}
}
html代码
用户名: | name="message" id="message" style="background-color: red"> |
密码: | |
type="reset" value="重置"> |
servlet 代码
//ajax验证用户名
public void checkUserName(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
System.out.println("进入checkUserName");
String name = (String)request.getParameter("name");
System.out.println(name);
UserDAO ud = new UserDAO();
boolean result = ud.checkUserName(name);
String message = "";
if(result){
message = "用户名可以使用";
}else{
message = "用户名已存在,请换个用户名!";
}
response.setContentType("text/html;charset=gb2312");
response.getOutputStream().write(message.getBytes());
response.getOutputStream().close();
}
java DAO层方法
//查询用户名是否存在
public boolean checkUserName(String name){
Connection conn = DataBaseUtil.getConnection();
String sql = "select * from user where name = ?";
PreparedStatement pstm=null;
ResultSet rs = null;
boolean result = true;
try{
pstm = conn.prepareStatement(sql);
pstm.setString(1,name);
rs = pstm.executeQuery();
if(rs.next()){
result = false;
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}