Jsp代码
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
</head>
<body>
<form action="register">
账号:<input name="userName"/><span id="show"></span><br>
密码:<input type="password" name="pwd"/><br>
<input type="submit" value="注册"/>
</form>
<script type="text/javascript">
$(function(){
$("[name=userName]").blur(function(){
$.ajax({
type:'post',
url:'findname?name='+$("[name=userName]").val(),
success:function(data){
if (data==1) {
$("#show").html("用户名已存在,请换一个");
} else {
$("#show").html("用户名可用");
}
}
});
});
});
</script>
</body>
</html>
servlet 代码
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
String name=request.getParameter("name");
TestDao td=new TestDaoImp();
Teacher ti= td.findTeacherName(name);
if (ti!=null) {
response.getWriter().write("1");
} else {
response.getWriter().write("2");
}
}
dao层代码
public interface TestDao {
public Teacher findTeacherName(String name);
}
dao层实现类代码
public class TestDaoImp implements TestDao{
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
@Override
public Teacher findTeacherName(String name) {
// TODO Auto-generated method stub
Teacher t=null;
try {
// 调用Util里的数据库连接方法
Connection conn = JDBCUtil.getConn();
// 编写sql语句
String sql = "select * from teacher where tname=?";
// 预编译sql语句
pst = conn.prepareStatement(sql);
// 给?赋值
pst.setString(1, name);
// 执行
rs = pst.executeQuery();
// 读取数据行
if (rs.next()) {
t= new Teacher();
t.setTid(rs.getInt(1));
t.setTname(rs.getString(2));
t.setTsex(rs.getString(3));
t.setAddress(rs.getString(4));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return t;
}
}
util连接数据库
public class JDBCUtil {
public static Connection getConn() {
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false", "root","123456");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
}
数据库用mysql,自己创建。不建议复制代码(不会成功),仅供参考。