SSH online mall using Ajax to complete the user name asynchronous verification

Time:2020-10-27

When the little partner is surfing the Internet, we need to download or watch some video materials, or when we are browsing Taobao, we need to register a user. When we fill in all kinds of information and click OK, the user name already exists. The editor thinks, why? When we fill in the user name, she will automatically prompt that the user name already exists. We also You don’t need to waste so much emotion until you fill in so much information. In the recent project of Xiaobian, we have encountered this problem. We can use ajax to complete whether the user name exists. Today, in this blog, I will simply summarize how to use ajax to complete the verification. Please give me more advice_ ∩*)′!

First of all, AJAX completes whether there is asynchronous verification of the user name, so what should we do? Here, we need to be triggered by an event, that is, when we enter the user name, the mouse moves away. This event is called onblur, that is, losing focus. On the contrary, we call it onfocus by placing the mouse in it to obtain the focus. Then how do we operate when we lose focus? First, find the registration page, find the code of the user name on the registration page, and then add onblur = checkusername() to verify the user name. Then we will write the method checkusername, and the specific code is as follows:

<span style="font-size:18px;">function checkUsername() { 
    //Get text box value: 
    var username = document.getElementById("username").value; 
    //1. Creating asynchronous interactive objects 
    var xhr = createXmlHttp(); 
    //2. Set up listening 
    xhr.onreadystatechange = function() { 
      if (xhr.readyState == 4) { 
        if (xhr.status == 200) { 
          document.getElementById("span1").innerHTML = xhr.responseText; 
        } 
      } 
    } 
    //3. Open connection 
    xhr.open("GET", 
        "${pageContext.request.contextPath}/user_findByName.action?time=" 
            + new Date().getTime() + "&username=", true) 
    //4. Send 
    xhr.send(null); 
  } 
  function createXmlHttp() { 
    var xmlHttp; 
    try { 
      xmlHttp = new XMLHttpRequest(); 
    } 
    catch (e) { 
      try { 
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 
      } 
       catch (e) { 
        try { 
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
        } catch (e) {} 
      } 
    } 
    return xmlHttp; 
  } 
</span>

Next, we will establish entity VO, realize model driven and automatic encapsulation. The specific code is as follows:


<span style="font-size:18px;">package cn.itcast.shop.user.vo; 
public class User { 
  private Integer uid; 
  private String username; 
  private String password; 
  private String name; 
  private String email; 
  private String phone; 
  private String addr; 
  private Integer state; 
  private String code; 
  public Integer getUid() { 
    return uid; 
  } 
  public void setUid(Integer uid) { 
    this.uid = uid; 
  } 
  public String getUsername() { 
    return username; 
  } 
  public void setUsername(String username) { 
    this.username = username; 
  } 
  public String getPassword() { 
    return password; 
  } 
  public void setPassword(String password) { 
    this.password = password; 
  } 
  public String getName() { 
    return name; 
  } 
  public void setName(String name) { 
    this.name = name; 
  } 
  public String getEmail() { 
    return email; 
  } 
  public void setEmail(String email) { 
    this.email = email; 
  } 
  public String getPhone() { 
    return phone; 
  } 
  public void setPhone(String phone) { 
    this.phone = phone; 
  } 
  public String getAddr() { 
    return addr; 
  } 
  public void setAddr(String addr) { 
    this.addr = addr; 
  } 
  public Integer getState() { 
    return state; 
  } 
  public void setState(Integer state) { 
    this.state = state; 
  } 
  public String getCode() { 
    return code; 
  } 
  public void setCode(String code) { 
    this.code = code; 
  } 
}</span> 

We need to receive parameters and implement model driven. Actionsupport can directly implement modelDriven. Then we can write our Ajax code, which needs to be submitted to action. We will write the code in useraction. The specific code is as follows:

<span style="font-size:18px;">package cn.itcast.shop.user.action; 
import java.io.IOException; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.struts2.ServletActionContext; 
import cn.itcast.shop.user.service.UserService; 
import cn.itcast.shop.user.vo.User; 
import com.opensymphony.xwork2.ActionSupport; 
import com.opensymphony.xwork2.ModelDriven; 
/** 
 *Class of user module action 
 * @author Flower 
 * 
 */ 
public class UserAction extends ActionSupport implements ModelDriven<User> { 
  //Objects used by model driven 
  private User user = new User(); 
  public User getModel(){ 
    return user; 
  } 
  //Injecting userservice 
  private UserService userService; 
  public void setUserService(UserService userService){ 
    this.userService=userService; 
  } 
  /** 
   *Execution method of jump to registration page 
   */ 
  public String registPage(){ 
    return "registPage"; 
  } 
  /** 
   *Implementation method of asynchronous user name verification with Ajax 
   * @throws IOException 
   */ 
  public String findByName() throws IOException{ 
    //Call service to query 
    User existUser = userService.findByUsername(user.getUsername()); 
    //Get the response object and output it to the page 
    HttpServletResponse response = ServletActionContext.getResponse(); 
    response.setContentType("text/html;charset=UTF-8"); 
    //Judgment 
    if(existUser != null){ 
      //Query the user: the user name already exists 
      response.getWriter (). Println ("< font color =" user name already exists < / font > "); 
    }else{ 
      //The user was not found: the user name can be used 
      response.getWriter (). Println ("< font color =" green > "user name already exists < / font >"); 
    } 
    return NONE; 
  } 
  /** 
   *User registration method: 
   */ 
  public String regist(){ 
    return NONE; 
  } 
} 
</span>

Next, what we need to do is to configure the service and Dao into the ApplicationContext. The code is as follows:

<span style="font- size:18px; "> <! -- configuration of service 
  <bean> 
    <property name="userDao" ref="userDao"/> 
  </bean>  
  <! -- configuration of userdao 
   <bean> 
    <property name="sessionFactory" ref="sessionFactory"></property> 
</bean> </span>

After configuration, we need to complete the query in userdao. The specific code is as follows:

<span style="font-size:18px;">package cn.itcast.shop.user.dao; 
import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 
import java.util.List; 
import cn.itcast.shop.user.vo.User; 
/** 
 *User module persistence layer code 
 * @author Flower 
 * 
 */ 
public class UserDao extends HibernateDaoSupport { 
  //Query whether there is the user by rank 
  public User findByUsername (String username){ 
    String hql ="from User where username= ?"; 
    List <User> list=this.getHibernateTemplate().find(hql,username); 
    if(list !=null && list.size() > 0){ 
      return list.get(0); 
    } 
     return null; 
    } 
} 
</span>

Next, we need to call Dao in service. The specific code is as follows:

<span style="font-size:18px;">package cn.itcast.shop.user.service; 
import org.springframework.transaction.annotation.Transactional; 
import cn.itcast.shop.user.dao.UserDao; 
import cn.itcast.shop.user.vo.User; 
/** 
 *User module business layer code 
 * @author Flower 
 * 
 */ 
@Transactional 
public class UserService { 
  //Injection of userdao 
  private UserDao userDao; 
  public void setUserDao(UserDao userDao){ 
    this.userDao =userDao; 
  } 
  //How to query users by user name 
  public User findByUsername (String username){ 
    return userDao.findByUsername(username); 
  } 
} 
</span>

Next, we need to call it in useraction. The specific code is as follows:

<span style="font-size:18px;">package cn.itcast.shop.user.action; 
import java.io.IOException; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.struts2.ServletActionContext; 
import cn.itcast.shop.user.service.UserService; 
import cn.itcast.shop.user.vo.User; 
import com.opensymphony.xwork2.ActionSupport; 
import com.opensymphony.xwork2.ModelDriven; 
/** 
 *Class of user module action 
 * @author Flower 
 * 
 */ 
public class UserAction extends ActionSupport implements ModelDriven<User> { 
  //Objects used by model driven 
  private User user = new User(); 
  public User getModel(){ 
    return user; 
  } 
  //Injecting userservice 
  private UserService userService; 
  public void setUserService(UserService userService){ 
    this.userService=userService; 
  } 
  /** 
   *Execution method of jump to registration page 
   */ 
  public String registPage(){ 
    return "registPage"; 
  } 
  /** 
   *Implementation method of asynchronous user name verification with Ajax 
   * @throws IOException 
   */ 
  public String findByName() throws IOException{ 
    //Call service to query 
    User existUser = userService.findByUsername(user.getUsername()); 
    //Get the response object and output it to the page 
    HttpServletResponse response = ServletActionContext.getResponse(); 
    response.setContentType("text/html;charset=UTF-8"); 
    //Judgment 
    if(existUser != null){ 
      //Query the user: the user name already exists 
      response.getWriter (). Println ("< font color =" user name already exists < / font > "); 
    }else{ 
      //The user was not found: the user name can be used 
      response.getWriter (). Println ("< font color =" green > "user name already exists < / font >"); 
    } 
    return NONE; 
  } 
  /** 
   *User registration method: 
   */ 
  public String regist(){ 
    return NONE; 
  } 
} 
</span>

Finally, we will write the contents of the mapping file. The specific code is as follows:


<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE hibernate-mapping PUBLIC  
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
  <hibernate-mapping> 
    <class name="cn.itcast.shop.user.vo.User" table="user"> 
      <id name="uid"> 
        <generator/> 
      </id> 
      <property name="username"/> 
      <property name="password"/> 
      <property name="name"/> 
      <property name="email"/> 
      <property name="phone"/> 
      <property name="addr"/> 
      <property name="state"/> 
      <property name="code"/> 
    </class> 
  </hibernate-mapping></span> 

Don’t forget to accompany her to the ApplicationContext. The specific code is as follows:

<span style="font- size:18px; "> <! -- configure other hibernate properties -- > 
    <property name="hibernateProperties"> 
      <props> 
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
        <prop key="hibernate.show_sql">true</prop> 
        <prop key="hibernate.format_sql">true</prop> 
        <prop key="hibernate.connection.autocommit">false</prop> 
        <prop key="hibernate.hbm2ddl.auto">update</prop> 
      </props> 
    </property> 
    <! -- configure hibernate mapping file -- > 
    <property name="mappingResources"> 
      <list> 
        <value>cn/itcast/shop/user/vo/User.hbm.xml</value> 
      </list> 
    </property> 
</span>

This is the end of the code. Let’s show you the following renderings:

Summary:   

The idea of implementation is like this_ Firstly, the event is triggered by onblur. Secondly, write the Ajax code, submit it to the action and pass the parameter username. The third step is to write the action, receive the username, and implement the model driven configuration to spring. The fourth step is to write Dao, integrate hibernate aosupport, inject sessionfactory into the configuration, and finally write service, inject userdao and transaction management Li, a simple demo, but also please give me more advice, SSH online mall, wonderful to be continued~~~