Preface
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.
Narration
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>
<td>
<input type="text" id="username" name="username" class="text" maxlength="20" onblur="checkUsername()" />
</td>
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)
xhr.open("GET", "${pageContext.request.contextPath}/user_findByName.action?time="+new Date().getTime()+"&username=" + username, true);
//4. send
xhr.send(null);
}
//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
package cn.itcast.shop.user.action;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import cn.itcast.shop.user.vo.User;
import cn.itcast.shop.user.service.UserService;
/**
* 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();
response.setContentType("text/html;charset=UTF-8");
// 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
package cn.itcast.shop.user.vo;
/**
* 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) {
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;
}
}
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"
"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 class="native"/>
</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>
4. Configure the mapping file into Spring (application Context. xml)
<property name="mappingResources">
<list>
<value>cn/itcast/shop/user/vo/User.hbm.xml</value>
</list>
</property>
IV. Writing DAO
1. Inheritance of Hibernate DaoSupport
package cn.itcast.shop.user.dao;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import cn.itcast.shop.user.vo.User;
/**
* User Module Persistence Layer Code
* @author Sunshine
*
*/
public class UserDao extends HibernateDaoSupport {
//Query by name if there is this user
@SuppressWarnings("unchecked")
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="cn.itcast.shop.user.dao.UserDao">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
Write Service:* 1. Injecting UserDao
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;
/**
* Business Layer Code of User Name Module
* @author Sunshine
*
*/
@Transactional
public class UserService {
//Inject UserDao
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.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="cn.itcast.shop.user.service.UserService">
<property name="userDao" ref="userDao" />
</bean>
Let's take a look at two pictures.
Summary
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