一、页面准备
<body>
<table border="1" width="500">
<tr>
<td>用户名:</td>
<td><input type="text" name="name" id="name" onblur="checkUserName()"><span id="span01"></span></td>
</tr>
<tr>
<td>密码</td>
<td><input type="text" name=""></td>
</tr>
<tr>
<td>邮箱</td>
<td><input type="text" name=""></td>
</tr>
<tr>
<td>简介</td>
<td><input type="text" name=""></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="注册"></td>
</tr>
</table>
</body>
二、Servlet代码
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
request.setCharacterEncoding("UTF-8");
// 1. 检测是否存在
String name = request.getParameter("name");
UserDao dao = new UserDaoImpl();
boolean isExist = dao.checkUserName(name);
System.out.println(isExist);
// 2. 通知页面,到底有还是没有。
if (isExist) {
response.getWriter().println(1);// 存在用户名
} else {
response.getWriter().println(2);// 不存在用户名
}
} catch (SQLException e) {
e.printStackTrace();
}
}
三、Dao代码
public class UserDaoImpl implements UserDao {
@Override
public boolean checkUserName(String name) throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil.getDataSource());
String sql = "select count(*) from t_user where username =?";
Long result = (Long) runner.query(sql, new ScalarHandler(), name);
System.out.println(result);
return result > 0;
}
}
四、JSP页面显示
1、get方式
function checkUserName(){
var request = ajaxFunction();
var name = document.getElementById("name").value;
request.onreadystatechange=function(){
if (request.readyState==4 && request.status==200){
var result = request.responseText;
if(result == 1){
document.getElementById("span1").innerHTML="<font color='red'>用户名已被占用</font>";
}else{
document.getElementById("span1").innerHTML="<font color='green'>用户名可以使用</font>";
}
}
}
request.open("GET", "RegisterServlet?name="+name, true);
request.send();
字符串比较:
if(result == '1'){
document.getElementById("span1").innerHTML="<font color='red'>用户名已被占用</font>";
}else{
document.getElementById("span1").innerHTML="<font color='green'>用户名可以使用</font>";
}
}
1、Post方式
function checkUserName() {
//获取输入框的值 document 整个网页
var name = document.getElementById("name").value; // value value() val val()
alert("name=" + name);
//1、创建对象
var request = ajaxFunction();
//2、发送请求
request.open("POST", "/AjaxDemo/CheckUserNameServlet", true);
//注册状态改变监听,获取服务器传送过来的数据
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
var data = request.responseText;
if (data == 1) {
document.getElementById("span1").innerHTML = "<font color='red'>用户名已存在!</font>";
} else {
document.getElementById("span1").innerHTML = "<font color='green'>用户名可用!</font>";
}
}
}
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("name=" + name);
}