【SSH网上商城】——AJAX异步验证是否存在该用户名

前端之家收集整理的这篇文章主要介绍了【SSH网上商城】——AJAX异步验证是否存在该用户名前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这几天抽着中午的空隙,敲SSH网上商城,刚开始敲的时候,弄SSH的框架花了段时间,框架搭完以后,开始首页跳转,一切都开始步入正轨了。敲了几集视频,感觉SSH网上商城的项目挺好玩的,虽然开始学习的时候不太懂,但是看着功能一个一个的实现,很有成就感。

使用ajax完成用户名是否存在的异步校验:一共分为五个步骤:


1.事件触发:

* 在用户名添加onblur事件
2.编写AJAX代码:
* 向Action中提交:传递username参数
3.编写Action
* 接收username:模型驱动接收.
* 编写实体类
* User
* User.hbm.xml
* 配置到Spring中.
4.编写DAO
* 继承HibernateDaoSupport
* 在配置中注入sessionFactory
5.编写Service

*注入UserDao

*事务管理

1、在注册页面找到用户名,为用户名添加onblur(鼠标失去焦点)事件

<strong><span style="font-size:18px;"><input type="text" id="username" name="username" class="text" maxlength="20" onblur="checkUsername()"/></span></strong>
2、编写AJAX代码:
<strong><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="+username,true);
		// 4.发送
		xhr.send(null);
	}
	
	function createXmlHttp(){
		   var xmlHttp;
		   try{ // Firefox,Opera 8.0+,Safari
		        xmlHttp=new XMLHttpRequest();
		    }
		    catch (e){
			   try{// Internet Explorer
			         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			      }
			    catch (e){
			      try{
			         xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			      }
			      catch (e){}
			      }
		    }

			return xmlHttp;
		 }</span></strong>
3.编写Action

在编写action前,需要先创建相应的包和类,要用到的user的包和类,见下图:


userAction: 接收username:模型驱动接收
package cn.itcast.shop.user;
import java.io.IOException;
import cn.itcast.shop.user.service.UserService;
import cn.itcast.shop.user.vo.User;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 用户模块Action的类
 * @author CXC
 *
 */
public class UserAction extends ActionSupport implements ModelDriven<User> {
	//模型驱动要使用的
	private User user=new User();
	public User getModel(){
		return user;		
	}
	//接受验证码:
	private String checkcode;
	
	public void setCheckcode(String checkcode){
		this.checkcode=checkcode;	
	}
	//注入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(){
		//判断验证码程序
		//从session中获得验证码的随机值
		String checkcode1=(String)ServletActionContext.getRequest().getSession().getAttribute("checkcode");
		if(!checkcode.equalsIgnoreCase(checkcode1)){
			this.addActionError("验证码输入错误!");
			return "checkcodeFail";			
		}
		userService.save(user);
		this.addActionMessage("注册成功!请去邮箱激活!");
		return "msg";		
		}
/**
 * 用户激活的方法
 */
	public String active(){
		//根据激活码查询用户:
		User existUser=userService.findByCode(user.getCode());
		//判断
		if(existUser ==null){
			//激活码错误
			this.addActionMessage("激活失败:激活码错误!");
		}else{
			//激活成功
			//修改用户的状态
			existUser.setState(1);
			existUser.setCode(null);
			userService.update(existUser);
			this.addActionMessage("激活成功,请去登陆!");
			
		}
		return "msg";
	}
	/**
	 * 跳转到登陆页面
	 */
	public String loginPage(){
		return "loginPage";
		
	}
	
	/**
	 * 登陆的方法
	 */
	public String login(){
		User existUser=userService.login(user);
		if(existUser==null){
			//登陆失败
			this.addActionError("登陆失败:用户名或密码错误用户未激活!");
			return LOGIN;
		}else{
			//登陆成功
			//将用户的信息存入到session中
			ServletActionContext.getRequest().getSession().setAttribute("existUser",existUser);
			return "loginSuccess";	
		}
	
	}
	/**
	 * 用户退出方法
	 */
	public String quit(){
		//销毁session
		ServletActionContext.getRequest().getSession().invalidate();
		return "quit";
	}
	
}


实体类:编写User的实体类
<strong><span style="font-size:18px;">package cn.itcast.shop.user.vo;
/**
 * 用户名模块实体类:
 * @author CXC
 *CREATE TABLE `user` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(255) DEFAULT NULL,`password` varchar(255) DEFAULT NULL,`name` varchar(255) DEFAULT NULL,`email` varchar(255) DEFAULT NULL,`phone` varchar(255) DEFAULT NULL,`addr` varchar(255) DEFAULT NULL,`state` int(11) DEFAULT NULL,`code` varchar(64) DEFAULT NULL,PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
 */
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></strong>

在User.hbm.xml中添加映射:

<strong><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></strong>

配置到Spring中:


4、编写Dao,在这块中UserDao继承HibernateDaoSupport

<strong style="font-family: Arial,Helvetica,sans-serif; font-size: 12px; background-color: rgb(255,255,255);"><span style="font-size:18px;"></span></strong>
<strong><span style="font-size:18px;">package cn.itcast.shop.user.dao;</span></strong>

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.itcast.shop.user.vo.User;


/*
 * 
 * 用户模块持久层代码:
 * @author CXC
 *
 */
public class UserDao extends HibernateDaoSupport{
	//按照名称查询是否有该用户:
	public User findByUsername(String username){
		String hql = "from User where username = ?";
		List<User> list = (List<User>) this.getHibernateTemplate().find(hql,username);
		if(list != null && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
	//注册用户存入数据库代码实现
	public void save(User user){
		this.getHibernateTemplate().save(user);
		
	}
	// 根据激活码查询用户
		public User findByCode(String code) {
			String hql = "from User where code = ?";
			List<User> list = (List<User>) this.getHibernateTemplate().find(hql,code);
			if(list != null && list.size() > 0){
				return list.get(0);
			}
			return null;
		}
	// 修改用户状态的方法
		public void update(User existUser) {
			this.getHibernateTemplate().update(existUser);
		}
		//用户登陆的方法
		public User login(User user) {
			// TODO Auto-generated method stub
			String hql="from User where username= ? and password = ? and state= ?";
			List<User> list=(List<User>) this.getHibernateTemplate().find(hql,user.getUsername(),user.getPassword(),1);
			if (list !=null && list.size()>0){
				return list.get(0);
				
			}
			return null;
		}
}

5、编写Service:将配置注入到sessionFactory中

<!-- 配置用户模块的Action -->
		<action name="user_*" class="userAction" method="{1}">
			<result name="registPage">/WEB-INF/jsp/regist.jsp</result>

事务管理:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	
	<!-- 配置连接池: -->
	<!-- 引入外部属性文件 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	
	<!-- 配置C3P0连接池 -->	
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driver}"/>
		<property name="jdbcUrl" value="${jdbc.url}"/>
		<property name="user" value="${jdbc.user}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>	
	
	<!-- Hibernate的相关信息 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionfactorybean">
		<!-- 注入连接池 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 配置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>
	</bean>
	
	<!-- 事务管理: -->
	<!-- 事务管理器 -->
	<bean id="transactionManager" class ="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	
	<!-- 开启注解事务  -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<!-- Action的配置  -->
	<!-- 首页访问的Action -->
	<bean id="indexAction" class="cn.itcast.shop.index.IndexAction" scope="prototype">
	<property name="categoryService" ref="categoryService"/>
	<property name="productService" ref="productService"/>
	</bean>
	
	
	<!-- 配置验证码的Action  -->
	<bean id="checkImgAction" class="cn.itcast.shop.user.CheckImgAction" scope="prototype"></bean>
	
	<!-- 用户模块的Action  -->
	<bean id='userAction' class="cn.itcast.shop.user.UserAction" scope="prototype">
	<!-- 注入Service -->
	<property name="userService" ref="userService"/>
	</bean>
	
	
	<!--  Service的配置   -->
	<bean id='userService' class="cn.itcast.shop.user.service.UserService">
	<property name="userDao" ref="userDao"/>
	</bean>
	
	<!--  Dao的配置  -->
	<bean id='userDao' class="cn.itcast.shop.user.dao.UserDao">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean> 
	

</beans>

总结:

刚开始学习SSH网上商城,接触到了好多东西,SSH(spring structs,hibernate)通过这个项目让我对以后的学习更感兴趣,通过敲这一条线,先来梳理一下简单的逻辑。

原文链接:https://www.f2er.com/ajax/162562.html

猜你在找的Ajax相关文章