您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關使用AJAX怎么實現(xiàn)一個注冊驗證用戶名功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據(jù)這篇文章可以有所收獲。
接口
public interface UserDao { public User findName(String name); }
接口實現(xiàn)類
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>
數(shù)據(jù)庫如下:
運行結果如下:
看完上述內容,你們對使用AJAX怎么實現(xiàn)一個注冊驗證用戶名功能有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業(yè)資訊頻道,感謝大家的支持。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。