一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

AJAX实现注册验证用户名代码示例

时间:2021-03-13 17:02:37 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下AJAX实现注册验证用户名代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

功能说明

当用户在注册页面输入用户名并且鼠标焦点离开输入框时,到数据表中去验证该用户名是否已经存在,如果存在提示不可用,否则,提示可用。

接口

public interface UserDao {
 public User findName(String name);
}

接口实现类

import 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;
 }
}

servlet

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页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

 
 AJAX实际操作注册验证用户名
 
 
 
 
账号
密码

数据库如下:

运行结果如下:

热门栏目