今天就跟大家聊聊有关使用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" %> <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>
数据库如下:
运行结果如下:
看完上述内容,你们对使用AJAX怎么实现一个注册验证用户名功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。