//jsp 文件中对于输入姓名框的验证 id=username 提示信息为id=usernameinfo
$(function(){
$("#username").blur(function(){
//1 获得input 框用户输入的值
var usernameInput = $(this).val();//$("#username").val();获取输入信息
//alert(usernameInput);
//2 去服务器验证用户名是否存在
$.post(
"${pageContext.request.contextPath}/checkUserServlet", //1url 地址
{"username":usernameInput}, //2 传输数据 传到url地址通过getparmeter("username")接收
function(data){
var isBoolean=data.isBoolean; //3用于接收response.getWriter().write("{"isBoolean":"+isBoolean+"}");传输的数据
var usernameinfo="";
if(isBoolean){
usernameinfo="该用户已经存在";//id=usernaeminfo 为提示信息
}else{
usernameinfo="该用户keyi注册";
}
$("#usernameinfo").html(usernameinfo);
}, //3 回调函数
"json" //4 传输数据类型
);
});
});
//${pageContext.request.contextPath}/checkUserServlet 跳转到的servlet文件 web 层
public class CheckUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
//System.out.println(username);
UserService ser= new UserService();
Boolean isBoolean=false;
try {
isBoolean=ser.checkUserName(username);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//{"isBoolean":isBoolean}
// System.out.println(isBoolean);
response.getWriter().write("{"isBoolean":"+isBoolean+"}");
}
//service层
package service;
import java.sql.SQLException;
import dao.UserDao;
public class UserService {
public Boolean checkUserName(String username) throws SQLException {
// TODO Auto-generated method stub
UserDao dao=new UserDao();
Long isBoolean = dao.checkUsername(username);
return isBoolean>0?true:false;
}
}
//dao层
package dao;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.DataSourceUtils;
public class UserDao {
public Long checkUsername(String username) throws SQLException {
// TODO Auto-generated method stub
QueryRunner run = new QueryRunner(DataSourceUtils.getDataSource());
String sql="select count(*) from user1 where username=?";
Long query = (Long)run.query(sql, new ScalarHandler(),username);
return query;
}
}