Ajax校验用户名是否存在的方法

本文实例为大家分享了Ajax验证用户名是否存在的实例代码,代码简单易懂,非常不错,需要的朋友可以参考下
【Ajax校验用户名是否存在的方法】jsp页面
我引入了bootstrap和jQuery


register.jsp页面

后台student文件下的CheckNameServlet页面
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//设置编码格式response.setContentType("text/html; charset=UTF-8"); //获取前端页面的值String name = request.getParameter("studentName"); // 期望服务器响应回的数据格式{"isExsit":true,"msg":"此用户名太受欢迎,请更换一个"}// {"userExsit":false,"msg":"此用户名已存在"}// 检验是否存在该用户名try {boolean isExist = StudentService.isExist(name); System.out.println("isExist" + isExist); Map map = new HashMap<>(); // 通知页面,到底有没有if (isExist) {map.put("isExist", true); map.put("msg", "此用户名太受欢迎,请更换一个"); } else {map.put("isExist", false); // map.put("msg", "用户名可用"); }//将map转换为json之前,要导包哦~// 将map转为json,并传递给客户端ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getWriter(), map); } catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace(); } }

JDBCDemo的方法的实现(我没实现接口,直接写的)
public static boolean checkName(String name) throws SQLException {boolean flag = false; String sql = "select * from student_table where student_name=?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, name); ResultSet set = statement.executeQuery(); 如果存在我输入的用户名和数据库表中已有的用户名相同时if(set.next()) {flag = true; }return flag; }}

总结:
以上所述是小编给大家介绍的Ajax验证用户名是否存在的实例代码,希望对大家有所帮助。

    推荐阅读