功能说明
( q% h, f; t6 | 当用户在注册页面输入用户名并且鼠标焦点离开输入框时,到数据表中去验证该用户名是否已经存在,如果存在提示不可用,否则,提示可用。
3 Q5 l8 E6 q3 X3 [接口: B9 s+ ^! u8 c$ V7 T1 }4 P# D# G0 d+ K
public interface UserDao {
public User findName(String name);
} 接口实现类
% o2 j; P; D) r* L3 j8 U! m* J; uimport java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao {
@Override
public User findName(String name) {
User user =null;
Connection conn = DBHelper.getConn();
String sql = "select * from user where name=?";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,name);
ResultSet rs = ps.executeQuery();
if (rs.next()){
user = new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
} servlet2 H* K5 q% j. M) R- C1 \7 s# `7 Z J
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/findName")
public class FindNameServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String name = request.getParameter("name");
UserDao userDao = new UserDaoImpl();
User name1 = userDao.findName(name);
if (name1!=null){
response.getWriter().write("1");
}else {
response.getWriter().write("2");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
} JSP页面
. R5 J7 o5 Q4 U5 ]. w- w/ f<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>AJAX实际操作注册验证用户名</title>
<script src="js/jquery-1.8.3.js"></script>
</head>
<body>
<form action="#" method="post">
<script type="text/javascript">
$(function () {
$("[name=userName]").blur(function () {
$.ajax({
type:"get",
url:"findName?name="+$("[name=userName]").val(),
dataType:"text",
success:function (data) {
//alert(data);
if (data=="1"){
$("#show").html("用户已存在!!!")
}else {
$("#show").html("用户名可用")
}
}
})
})
});
</script>
账号<input type="text" name="userName"><span id="show"></span></br>
密码<input type="password" name="password"></br>
<input type="submit" value="提交">
</form>
</body>
</html> 数据库如下:
" A* x# q: f( H' y! H9 @; R
0 g8 F: j1 w. g运行结果如下:8 w3 ]! S( ]$ e
& x" z Z" G, o- ^2 Z! b/ t$ o) K; b& ?
|