小伙伴在上網的時候,需要下載或者觀看某些視頻資料,更或者是在逛淘寶的時候,我們都需要注冊一個用戶,當我們填寫好各種信息,點擊確定的時候,提示用戶名已經存在,小編就想,為什麼當我們填寫完用戶名的時候,她就自動提示用戶名已經存在,我們也不需要浪費那麼多感情,直到填寫完那麼多的信息之後在提示,在小編最近的項目中,就碰到這個問題,我們可以使用ajax完成用戶名是否存在,今天這篇博客,小編就簡單的總結一下,如何使用ajax來完成校驗,還請小伙伴多多指教哦`(*∩_∩*)′!
首先ajax完成用戶名是否存在異步校驗,那麼我們該如何做呢?在這裡,我們要由事件進行觸發,也就是說,我們在用戶名裡面輸入的時候,鼠標移開,這個事件叫做onblur,即失去焦點,與其相對的,鼠標放在裡面獲得焦點,我們稱之為onfocus,那麼失去焦點,我們該怎麼操作呢?首先找到注冊頁面,在注冊頁面找到用戶名那部分的代碼,在後面加上onblur=checkUsername(),校驗用戶名即可,接著我們來編寫方法checkUsername,具體代碼如下所示:
<span style="font-size:18px;">function checkUsername() { //獲取文本框值: var username = document.getElementById("username").value; //1、創建異步交互對象 var xhr = createXmlHttp(); //2、設置監聽 xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { document.getElementById("span1").innerHTML = xhr.responseText; } } } //3、打開連接 xhr.open("GET", "${pageContext.request.contextPath}/user_findByName.action?time=" + new Date().getTime() + "&username=", true) //4、發送 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>
接著,我們來建立實體Vo,實現模型驅動,自動實現封裝,具體代碼如下所示:
<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>
我們要接收參數,實現模型驅動,ActionSupport直接實現modelDriven即可,接著來編寫我們的ajax代碼,需要向action中進行提交,我們來編寫UserAction中的代碼,具體代碼如下所示:
<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; /** * 用戶模塊Action的類 * @author Flower * */ public class UserAction extends ActionSupport implements ModelDriven<User> { //模型驅動使用的對象 private User user = new User(); public User getModel(){ return user; } //注入UserService private UserService userService; public void setUserService(UserService userService){ this.userService=userService; } /** * 跳轉到注冊頁面的執行方法 */ public String registPage(){ return "registPage"; } /** * ajax進行異步校驗用戶名的執行方法 * @throws IOException */ public String findByName() throws IOException{ //調用Service進行查詢 User existUser = userService.findByUsername(user.getUsername()); //獲得response對象,向頁面輸出 HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); //判斷 if(existUser != null){ //查詢到該用戶:用戶名已經存在 response.getWriter().println("<font color='red'>用戶名已經存在</font>"); }else{ //沒查詢到該用戶:用戶名可以使用 response.getWriter().println("<font color='green'>用戶名已經存在</font>"); } return NONE; } /** * 用戶注冊的方法: */ public String regist(){ return NONE; } } </span>
接著,我們需要做的就是把service和Dao配置到applicationContext中,代碼如下所示:
<span style="font-size:18px;"><!-- Service的配置 =========================== --> <bean id="userService" class="cn.itcast.shop.user.service.UserService"> <property name="userDao" ref="userDao"/> </bean> <!-- UserDao的配置 =========================== --> <bean id="userDao" class="cn.itcast.shop.user.dao.UserDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </span>
配置好了之後,我們需要在UserDao裡面完成查詢,具體代碼如下所示:
<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; /** * 用戶模塊持久層代碼 * @author Flower * */ public class UserDao extends HibernateDaoSupport { //按名次查詢是否有該用戶 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>
接著,我們需要在service裡面完成對Dao的調用,具體代碼如下所示:
<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; /** * 用戶模塊業務層代碼 * @author Flower * */ @Transactional public class UserService { //注入UserDao private UserDao userDao; public void setUserDao(UserDao userDao){ this.userDao =userDao; } //按用戶名查詢用戶的方法 public User findByUsername (String username){ return userDao.findByUsername(username); } } </span>
接著我們需要在UserAction中進行調用,具體代碼如下所示:
<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; /** * 用戶模塊Action的類 * @author Flower * */ public class UserAction extends ActionSupport implements ModelDriven<User> { //模型驅動使用的對象 private User user = new User(); public User getModel(){ return user; } //注入UserService private UserService userService; public void setUserService(UserService userService){ this.userService=userService; } /** * 跳轉到注冊頁面的執行方法 */ public String registPage(){ return "registPage"; } /** * ajax進行異步校驗用戶名的執行方法 * @throws IOException */ public String findByName() throws IOException{ //調用Service進行查詢 User existUser = userService.findByUsername(user.getUsername()); //獲得response對象,向頁面輸出 HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); //判斷 if(existUser != null){ //查詢到該用戶:用戶名已經存在 response.getWriter().println("<font color='red'>用戶名已經存在</font>"); }else{ //沒查詢到該用戶:用戶名可以使用 response.getWriter().println("<font color='green'>用戶名已經存在</font>"); } return NONE; } /** * 用戶注冊的方法: */ public String regist(){ return NONE; } } </span>
最後,我們來編寫映射文件裡面的內容,具體代碼如下所示:
<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 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></span>
不要忘記了,要把她陪到applicationContext裡面,具體代碼如下所示:
<span style="font-size:18px;"><!-- 配置Hibernate的其他的屬性 --> <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> <!-- 配置Hibernate的映射文件 --> <property name="mappingResources"> <list> <value>cn/itcast/shop/user/vo/User.hbm.xml</value> </list> </property> </span>
代碼到此結束,下面給大家展示下效果圖:
小編總結:
實現的思路是這樣滴`(*∩_∩*)′,首先是由onblur進行事件觸發,第二,編寫ajax的代碼,向action中提交,傳遞參數username,第三步,編寫action,接收username,實現模型驅動配置到spring中,第四步,編寫DAO,集成HibernateDaoSupport,在配置中注入sessionFactory,最後編寫Service,注入UserDao,還有事務管理,一個簡單的demo,還請小伙伴多多指教,SSH網上商城,精彩未完待續~~~