SSH网上商城之使用ajax完成用户名是否存在异步校验
小伙伴在上网的时候,需要下载或者观看某些视频资料,更或者是在逛淘宝的时候,我们都需要注册一个用户,当我们填写好各种信息,点击确定的时候,提示用户名已经存在,小编就想,为什么当我们填写完用户名的时候,她就自动提示用户名已经存在,我们也不需要浪费那么多感情,直到填写完那么多的信息之后在提示,在小编最近的项目中,就碰到这个问题,我们可以使用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网上商城,精彩未完待续~~~