Using AJAX asynchronous loading to verify the existence of user names


Asynchronous loading of AJAX has always been a platitudinal topic. When it comes to AJAX, the most important thing to think about is its asynchronous loading. Recently, the editor let the asynchronous loading of AJAX play a role in the project. Let's see how it demonstrates its ability.


Asynchronous loading of AJAX: A technique for obtaining server content without reloading pages.

Examples are given to illustrate:

Usually, when a user registers, the user first fills in the form and then clicks to submit it it, so that the form will send a request to the service, then the server processes the code and returns a message if the user exists. In short, all the data needs to be submitted before the information can be sent!
AJAX is equivalent to simulating a request for sending information. When you register on many websites, you will find that if the user name enters "123", it may prompt you that the user already exists, and give you the feeling that the page has not been refreshed, that is, the form has not been submitted, and the user name is stored in the database, that is to say, to query the user. Whether the name exists or not, you have to send the user name in the form, and then query it in the database.
This process is handled by AJAX. When the user enters the username, when the focus of the form changes, it triggers AJAX. Then AJAX simulates a GET or POST request to the server, and the server will process the transferred data. While the server is processing data, you can do other things, compare you can fill in passwords or other!

The following example will use ajax to determine whether a user name exists at the time of registration

This example is implemented in SSH framework, which is divided into the following five steps.

1. Event triggering:

  * onblur

2. Write AJAX code:

* Submit in Item Action: Pass the username parameter

3. Writing Action

* Receiving username: Model-driven Receiving.

* Writing Entity Classes

   * User

   * User.hbm.xml

* Configure to Spring.

4. writing DAO

* Inheriting Hibernate DaoSupport

* Injecting sessionFactory into the configuration

5. Write Service:

* Inject UserDao

* Transaction management:

1. Event triggering:

1. Find a line of username on the registration page (register. jsp) and add onblur to it.

<th><span class="requiredField">*</span>User name:</th>
	<input type="text" id="username" name="username" class="text" maxlength="20" onblur="checkUsername()" /> 


2. Write AJAX code:

1. Write the checkUsername method (AJAX): Pass the username parameter

function checkUsername() {
	//Get the value of the text box
	var username = document.getElementById("username").value;
	//Traditional asynchronous verification
	//1. Creating asynchronous interactive objects
	var xhr = createXmlHttp();
	//2. Setting up monitoring
	xhr.onreadystatechange = function() {
	   if (xhr.readyState == 4) {
		if (xhr.status == 200) {
			document.getElementById("span1").innerHTML = xhr.responseText;

	//3. Open connection parameters (request mode, request path, asynchronous setting)"GET", "${pageContext.request.contextPath}/user_findByName.action?time="+new Date().getTime()+"&username=" + username, true);
	//4. send

//create object
function createXmlHttp() {
	var xmlHttp;
	try {
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		try {
			xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
	return xmlHttp;

III. Writing Action

1. userAction: Receiving username: Model Driven Receiving



import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;



 * Classes of User Module Action
 * @author Sunshine
public class UserAction extends ActionSupport implements ModelDriven<User>{
	//Model-driven objects to be used
	private User user=new User();
	public User getModel(){
		return user;

	//Inject UserService
	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;

	 * AJAX Execution method for asynchronous verification of user names
	 * @throws IOException
	public String findByName() throws IOException {
		// Call Service to query:
		User existUser = userService.findByUsername(user.getUsername());
		// Get the response object, item page output:
		HttpServletResponse response = ServletActionContext.getResponse();
		// judge
		if (existUser != null) {
			// Query to the user: the user name already exists
			response.getWriter().println("<font color='red'>User name already exists</font>");
		} else {
			// The user was not queried: the username can be used
			response.getWriter().println("<font color='green'>User names can be used</font>");
		return NONE;
2. Entity Class: Write User's Entity Class


 * Entity class of user module
 * @author Sunshine
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) { = name;
	public String getEmail() {
		return email;
	public void setEmail(String email) { = email;
	public String getPhone() {
		return phone;
	public void setPhone(String 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;
3. Add mappings in User.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	<class name="" table="user">
		<id name="uid">
			<generator class="native"/>
		<property name="username"/>
		<property name="password"/>
		<property name="name"/>
		<property name="email"/>
		<property name="phone"/>
		<property name="addr"/>
		<property name="state"/>
		<property name="code"/>
4. Configure the mapping file into Spring (application Context. xml)

<property name="mappingResources">

IV. Writing DAO
1. Inheritance of Hibernate DaoSupport
import java.util.List;

 * User Module Persistence Layer Code
 * @author Sunshine
public class UserDao extends HibernateDaoSupport {
	//Query by name if there is this user
	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;

2. Injecting session Factory into the application Context. XML configuration

<!--Dao Configuration -->
	<bean id="userDao" class="">
		<property name="sessionFactory" ref="sessionFactory"/>
Write Service:
* 1. Injecting UserDao


import org.springframework.transaction.annotation.Transactional;


 * Business Layer Code of User Name Module
 * @author Sunshine

public class UserService {
	//Inject UserDao
	private UserDao userDao;
	public void setUserDao(UserDao userDao){
	//A Method of Querying Users by User Name
	public User findByUsername(String username){
		return userDao.findByUsername(username);

2. Transaction management:

	<!--Service Configuration -->
	<bean id="userService" class="">
		<property name="userDao" ref="userDao" />

Let's take a look at two pictures.


In fact, the above steps are basically a basic step in the practical application of SSH framework. In the process of learning, the train of thought is clear, and then everything is easy to do.

What is the SSH framework? See the last blog of Xiaobian.   SSH framework

Keywords: Hibernate xml ssh Database

Added by blues on Fri, 17 May 2019 12:15:58 +0300