ajax and servlet -- Verify that the user name exists

Posted by splitinfo on Fri, 17 Jul 2020 16:26:13 +0200

Verify that the user name exists -- using jQuery

1. Database mysql

The user name already exists in the database.

2. html Page

    <h1>User Login</h1>
    <form name="regForm" action="dologin.jsp" method="post">
                <td><input id="Name"  type="text" name="username"/><span id="msg">Please enter a nickname</span></td>
                <td><input type="password" name="password"/></td>
                <td colspan="2"><input type="submit" value="submit"/></td>
        <a href="/myblog/register.jsp">No account?Register now.</a>  

3. jQuery Code--ajax

When the user name in the form loses focus, the Ajax is triggered to interact with the back-end Ajax class.

  <script type="text/javascript" src="${path}js/jquery-3.1.1.js"></script>
  <script type="text/javascript"> 
			 var user = {username:$("#Name").val()};
			 $("#msg").html(result); }

4. Background ClassesAjax.java

The DB class is referenced in this class to facilitate the creation of database instances.The class interacts with the database and returns data to the front end.

public class Ajax extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("username");
		//Connect to database
		try{	//Create a connection to the database
		Connection conn = DB.getConn();
		//sql statement
		String sql ="SELECT * FROM admin where username= ? ";
		PreparedStatement pstm = conn.prepareStatement(sql);
		pstm.setString(1, name);
		 ResultSet rs = pstm.executeQuery();
				 response.getWriter().print("Your username is already registered");
				response.getWriter().print("Verification successful");
		 }catch(Exception e){


5. In Ajax.java Use DB class

Create a database instance.

public class DB {
	private static Connection conn =null;

	private DB(){
	public static Connection getConn(){
		if (conn != null) {
			return conn;
		String url = "jdbc:mysql://localhost/webuser?useUnicode=true&characterEncoding=utf-8&useSSL=false";

		conn= DriverManager.getConnection(url,"root", "17911");
		return conn;
		}catch(Exception e){
			return null;

6. Operation results

When not entered:

jsh is a registered user:

New users:

7. Prospect

There's not much rubbish on it. Write code for html, js, servlet directly. Write javaweb student information management system should be used.

Next time it should be the source code of the student information management system.

Topics: Database JQuery MySQL SQL