Ajax+SpringMVC+Spring+Mybatis+MySql+js用户注册实例

林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka

摘要:这几天研究了下Ajax注册的方法,通过在注册时输入用户名或邮箱等,就可以判断这个用户是否存在,以免用户来注册,然后提交了,系统才提示该用户名或邮箱不可用。使用Ajax便可实现这一功能,看了网上的都是php的,想想索性来写一个SpringMVC+Spring+Mybatis的。文章内容用到了很多技术,包括javascript、jquery、json、e表达式等。

先来看看最终效果:

注册成功的样子:

注册过程中参数的检验:

下面,让我们开始这次的编程吧!

首先,数据库准备,新建一张用户表,并自己插入一些数据

CREATE TABLE
    t_user
    (
        USER_ID INT NOT NULL AUTO_INCREMENT,
        USER_NAME CHAR(30) NOT NULL,
        USER_PASSWORD CHAR(10) NOT NULL,
        USER_EMAIL CHAR(30) NOT NULL,
        PRIMARY KEY (USER_ID)
    )
    ENGINE=InnoDB DEFAULT CHARSET=utf8;

好,数据库建好了,接下来就是整个工程了。

一、工程整体

项目类型:Dynamic Web Project

开发环境:

Eclipse Java EE IDE for Web Developers.
Version: Luna Service Release 2 (4.4.2)
Build id: 20150219-0600

JDK版本:

jdk1.6.0_45

本文工程免费下载

工程的其它参数:

1、用到的JAR包

json使用的包。这里下载

spring+sprngMvc的包。

mybatis的包

mysql连接的包

logger的包(日记 打印的)

如下:

2、需要的外部js

jquery-1.11.3.min.js

3、项目结构

这是还没有展开的

然后把各个都展开:

其中src放置java的文件、config放置SpringMVC+Spring+Mybatis的配置文件以及日记打印的log4j.properties

web-inf下面:js用来放置调用 的js文件,lib就是最上面说的jar包的位置,view是各个jsp文件

二、编程

2.1 java代码

这里分了5层,按照标准的web工程来

1、domain层

这里是使用Mybatis Generator自动生成的:User.java

package com.lin.domain;

public class User {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_user.USER_ID
     *
     * @mbggenerated
     */
    private Integer userId;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_user.USER_NAME
     *
     * @mbggenerated
     */
    private String userName;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_user.USER_PASSWORD
     *
     * @mbggenerated
     */
    private String userPassword;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_user.USER_EMAIL
     *
     * @mbggenerated
     */
    private String userEmail;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column t_user.USER_ID
     *
     * @return the value of t_user.USER_ID
     *
     * @mbggenerated
     */
    public Integer getUserId() {
        return userId;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column t_user.USER_ID
     *
     * @param userId the value for t_user.USER_ID
     *
     * @mbggenerated
     */
    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column t_user.USER_NAME
     *
     * @return the value of t_user.USER_NAME
     *
     * @mbggenerated
     */
    public String getUserName() {
        return userName;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column t_user.USER_NAME
     *
     * @param userName the value for t_user.USER_NAME
     *
     * @mbggenerated
     */
    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column t_user.USER_PASSWORD
     *
     * @return the value of t_user.USER_PASSWORD
     *
     * @mbggenerated
     */
    public String getUserPassword() {
        return userPassword;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column t_user.USER_PASSWORD
     *
     * @param userPassword the value for t_user.USER_PASSWORD
     *
     * @mbggenerated
     */
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword == null ? null : userPassword.trim();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column t_user.USER_EMAIL
     *
     * @return the value of t_user.USER_EMAIL
     *
     * @mbggenerated
     */
    public String getUserEmail() {
        return userEmail;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column t_user.USER_EMAIL
     *
     * @param userEmail the value for t_user.USER_EMAIL
     *
     * @mbggenerated
     */
    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail == null ? null : userEmail.trim();
    }
}

然后还有一个example文件:UserExample.java

package com.lin.domain;

import java.util.ArrayList;
import java.util.List;

public class UserExample {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table t_user
     *
     * @mbggenerated
     */
    protected String orderByClause;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table t_user
     *
     * @mbggenerated
     */
    protected boolean distinct;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table t_user
     *
     * @mbggenerated
     */
    protected List<Criteria> oredCriteria;

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public UserExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public String getOrderByClause() {
        return orderByClause;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public boolean isDistinct() {
        return distinct;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table t_user
     *
     * @mbggenerated
     */
    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        public Criteria andUserIdIsNull() {
            addCriterion("USER_ID is null");
            return (Criteria) this;
        }

        public Criteria andUserIdIsNotNull() {
            addCriterion("USER_ID is not null");
            return (Criteria) this;
        }

        public Criteria andUserIdEqualTo(Integer value) {
            addCriterion("USER_ID =", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdNotEqualTo(Integer value) {
            addCriterion("USER_ID <>", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdGreaterThan(Integer value) {
            addCriterion("USER_ID >", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdGreaterThanOrEqualTo(Integer value) {
            addCriterion("USER_ID >=", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdLessThan(Integer value) {
            addCriterion("USER_ID <", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdLessThanOrEqualTo(Integer value) {
            addCriterion("USER_ID <=", value, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdIn(List<Integer> values) {
            addCriterion("USER_ID in", values, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdNotIn(List<Integer> values) {
            addCriterion("USER_ID not in", values, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdBetween(Integer value1, Integer value2) {
            addCriterion("USER_ID between", value1, value2, "userId");
            return (Criteria) this;
        }

        public Criteria andUserIdNotBetween(Integer value1, Integer value2) {
            addCriterion("USER_ID not between", value1, value2, "userId");
            return (Criteria) this;
        }

        public Criteria andUserNameIsNull() {
            addCriterion("USER_NAME is null");
            return (Criteria) this;
        }

        public Criteria andUserNameIsNotNull() {
            addCriterion("USER_NAME is not null");
            return (Criteria) this;
        }

        public Criteria andUserNameEqualTo(String value) {
            addCriterion("USER_NAME =", value, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameNotEqualTo(String value) {
            addCriterion("USER_NAME <>", value, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameGreaterThan(String value) {
            addCriterion("USER_NAME >", value, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameGreaterThanOrEqualTo(String value) {
            addCriterion("USER_NAME >=", value, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameLessThan(String value) {
            addCriterion("USER_NAME <", value, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameLessThanOrEqualTo(String value) {
            addCriterion("USER_NAME <=", value, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameLike(String value) {
            addCriterion("USER_NAME like", value, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameNotLike(String value) {
            addCriterion("USER_NAME not like", value, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameIn(List<String> values) {
            addCriterion("USER_NAME in", values, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameNotIn(List<String> values) {
            addCriterion("USER_NAME not in", values, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameBetween(String value1, String value2) {
            addCriterion("USER_NAME between", value1, value2, "userName");
            return (Criteria) this;
        }

        public Criteria andUserNameNotBetween(String value1, String value2) {
            addCriterion("USER_NAME not between", value1, value2, "userName");
            return (Criteria) this;
        }

        public Criteria andUserPasswordIsNull() {
            addCriterion("USER_PASSWORD is null");
            return (Criteria) this;
        }

        public Criteria andUserPasswordIsNotNull() {
            addCriterion("USER_PASSWORD is not null");
            return (Criteria) this;
        }

        public Criteria andUserPasswordEqualTo(String value) {
            addCriterion("USER_PASSWORD =", value, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordNotEqualTo(String value) {
            addCriterion("USER_PASSWORD <>", value, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordGreaterThan(String value) {
            addCriterion("USER_PASSWORD >", value, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordGreaterThanOrEqualTo(String value) {
            addCriterion("USER_PASSWORD >=", value, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordLessThan(String value) {
            addCriterion("USER_PASSWORD <", value, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordLessThanOrEqualTo(String value) {
            addCriterion("USER_PASSWORD <=", value, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordLike(String value) {
            addCriterion("USER_PASSWORD like", value, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordNotLike(String value) {
            addCriterion("USER_PASSWORD not like", value, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordIn(List<String> values) {
            addCriterion("USER_PASSWORD in", values, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordNotIn(List<String> values) {
            addCriterion("USER_PASSWORD not in", values, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordBetween(String value1, String value2) {
            addCriterion("USER_PASSWORD between", value1, value2, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserPasswordNotBetween(String value1, String value2) {
            addCriterion("USER_PASSWORD not between", value1, value2, "userPassword");
            return (Criteria) this;
        }

        public Criteria andUserEmailIsNull() {
            addCriterion("USER_EMAIL is null");
            return (Criteria) this;
        }

        public Criteria andUserEmailIsNotNull() {
            addCriterion("USER_EMAIL is not null");
            return (Criteria) this;
        }

        public Criteria andUserEmailEqualTo(String value) {
            addCriterion("USER_EMAIL =", value, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailNotEqualTo(String value) {
            addCriterion("USER_EMAIL <>", value, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailGreaterThan(String value) {
            addCriterion("USER_EMAIL >", value, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailGreaterThanOrEqualTo(String value) {
            addCriterion("USER_EMAIL >=", value, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailLessThan(String value) {
            addCriterion("USER_EMAIL <", value, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailLessThanOrEqualTo(String value) {
            addCriterion("USER_EMAIL <=", value, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailLike(String value) {
            addCriterion("USER_EMAIL like", value, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailNotLike(String value) {
            addCriterion("USER_EMAIL not like", value, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailIn(List<String> values) {
            addCriterion("USER_EMAIL in", values, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailNotIn(List<String> values) {
            addCriterion("USER_EMAIL not in", values, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailBetween(String value1, String value2) {
            addCriterion("USER_EMAIL between", value1, value2, "userEmail");
            return (Criteria) this;
        }

        public Criteria andUserEmailNotBetween(String value1, String value2) {
            addCriterion("USER_EMAIL not between", value1, value2, "userEmail");
            return (Criteria) this;
        }
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table t_user
     *
     * @mbggenerated do_not_delete_during_merge
     */
    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table t_user
     *
     * @mbggenerated
     */
    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value) {
            super();
            this.condition = condition;
            this.value = value;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.betweenValue = true;
        }
    }
}

2、dao层

这里是使用Mybatis Generator自动生成的:UserDao.java

package com.lin.dao;

import com.lin.domain.User;
import com.lin.domain.UserExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface UserDao {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    int countByExample(UserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    int deleteByExample(UserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    int deleteByPrimaryKey(Integer userId);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    int insert(User record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    int insertSelective(User record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    List<User> selectByExample(UserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    User selectByPrimaryKey(Integer userId);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    int updateByExample(@Param("record") User record, @Param("example") UserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    int updateByPrimaryKeySelective(User record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbggenerated
     */
    int updateByPrimaryKey(User record);
}

3、service层

这里就设计了两个方法,一个查找和一个插入

接口类:

package com.lin.service;

import com.lin.domain.User;
import com.lin.domain.UserExample;

public interface IRegisterService {

	public int insert(User record);

	public int countByExample(UserExample example);

}

实现类:

package com.lin.service.impl;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.lin.dao.UserDao;
import com.lin.domain.User;
import com.lin.domain.UserExample;
import com.lin.service.IRegisterService;
@Service("registerService")
public class RegisterServiceImpl implements IRegisterService{
	private static Logger logger = Logger.getLogger(RegisterServiceImpl.class);
	@Resource
	private UserDao userDao;

	@Override
	public int insert(User record) {
		try {
			return userDao.insert(record);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int countByExample(UserExample example) {
		try {
			return userDao.countByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

}

2.2 配置文件

1、mappp文件配置

这里是使用Mybatis Generator自动生成的:UserMapper.xml。放在src下面的com.lin.mapper包下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lin.dao.UserDao">
  <resultMap id="BaseResultMap" type="com.lin.domain.User">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="USER_ID" jdbcType="INTEGER" property="userId" />
    <result column="USER_NAME" jdbcType="CHAR" property="userName" />
    <result column="USER_PASSWORD" jdbcType="CHAR" property="userPassword" />
    <result column="USER_EMAIL" jdbcType="CHAR" property="userEmail" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL
  </sql>
  <select id="selectByExample" parameterType="com.lin.domain.UserExample" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from t_user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select
    <include refid="Base_Column_List" />
    from t_user
    where USER_ID = #{userId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from t_user
    where USER_ID = #{userId,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.lin.domain.UserExample">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from t_user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.lin.domain.User">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    insert into t_user (USER_ID, USER_NAME, USER_PASSWORD,
      USER_EMAIL)
    values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=CHAR}, #{userPassword,jdbcType=CHAR},
      #{userEmail,jdbcType=CHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.lin.domain.User">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    insert into t_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="userId != null">
        USER_ID,
      </if>
      <if test="userName != null">
        USER_NAME,
      </if>
      <if test="userPassword != null">
        USER_PASSWORD,
      </if>
      <if test="userEmail != null">
        USER_EMAIL,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="userId != null">
        #{userId,jdbcType=INTEGER},
      </if>
      <if test="userName != null">
        #{userName,jdbcType=CHAR},
      </if>
      <if test="userPassword != null">
        #{userPassword,jdbcType=CHAR},
      </if>
      <if test="userEmail != null">
        #{userEmail,jdbcType=CHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.lin.domain.UserExample" resultType="java.lang.Integer">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select count(*) from t_user
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update t_user
    <set>
      <if test="record.userId != null">
        USER_ID = #{record.userId,jdbcType=INTEGER},
      </if>
      <if test="record.userName != null">
        USER_NAME = #{record.userName,jdbcType=CHAR},
      </if>
      <if test="record.userPassword != null">
        USER_PASSWORD = #{record.userPassword,jdbcType=CHAR},
      </if>
      <if test="record.userEmail != null">
        USER_EMAIL = #{record.userEmail,jdbcType=CHAR},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update t_user
    set USER_ID = #{record.userId,jdbcType=INTEGER},
      USER_NAME = #{record.userName,jdbcType=CHAR},
      USER_PASSWORD = #{record.userPassword,jdbcType=CHAR},
      USER_EMAIL = #{record.userEmail,jdbcType=CHAR}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.lin.domain.User">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update t_user
    <set>
      <if test="userName != null">
        USER_NAME = #{userName,jdbcType=CHAR},
      </if>
      <if test="userPassword != null">
        USER_PASSWORD = #{userPassword,jdbcType=CHAR},
      </if>
      <if test="userEmail != null">
        USER_EMAIL = #{userEmail,jdbcType=CHAR},
      </if>
    </set>
    where USER_ID = #{userId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.lin.domain.User">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update t_user
    set USER_NAME = #{userName,jdbcType=CHAR},
      USER_PASSWORD = #{userPassword,jdbcType=CHAR},
      USER_EMAIL = #{userEmail,jdbcType=CHAR}
    where USER_ID = #{userId,jdbcType=INTEGER}
  </update>
</mapper>

2、mybatis配置,没有其实也行,因为都 在spring中进行配置了,但是保留一下,以免要用,mybatis-config.xml放在config下面

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

3、spingMVC配置

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!-- 把标记了@Controller注解的类转换为bean -->
    <context:component-scan base-package="com.lin.controller" />
    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
   <!-- 静态资源访问(不拦截此目录下的东西的访问) -->
    <mvc:annotation-driven />
    <mvc:resources location="/WEB-INF//js/"  mapping="/js/**" />
    <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>  

</beans>

4、spring配置:application.xml放在config下面

<?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"
	xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<!-- 配置数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/learning" />
		<property name="username" value="root" />
		<property name="password" value="[email protected]" />
	</bean>

	<!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage"
			value="com.lin.dao" />
	</bean>

<!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
       <property name="mapperLocations" value="classpath*:com/lin/mapper/**/*.xml"/>
		<property name="configLocation" value="classpath:mybatis-config.xml" />
		<!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"
			/> -->
	</bean>

	<!-- 自动扫描注解的bean -->
	<context:component-scan base-package="com.lin.controller" />
		<context:component-scan base-package="com.lin.service.impl" />

</beans>

5、日志打印配置:log4j.properties放在config下面

log4j.rootLogger =DEBEG,stdout,debug

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n  

log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG 

6、web文件配置,放在WebContent下面

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>JsLearning3</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

        <!-- Spring 容器加载 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param> 

    <!-- 统一设置编码,防止出现中文乱码 -->
  	<filter>
		<filter-name>Set Character Encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>Set Character Encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

   <!-- SpringMVC的前端控制器 -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 设置自己定义的控制器xml文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- Spring MVC配置文件结束 -->  

    <!-- 拦截设置 -->
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!-- 由SpringMVC拦截所有请求 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>  

    <!-- webAppRootKey:值缺省为webapp.root,当tomcat下部署多个应用时(每个都用到了log4j), 每个应用的web.xml中都要配置该参数,该参数与Log4j.xml文件中的${webapp.root}
        否则每个应用的webAppRootKey值都相同,就会引起冲突
     -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>webApp.root</param-value>
    </context-param>
    <!-- log4jConfigLocation:log4j配置文件存放路径 -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>
    <!-- 3000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;这样便于日志存放位置的改变 -->
    <context-param>
         <param-name>log4jRefreshInterval</param-name>
         <param-value>3000</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
</web-app>

三、web页面编写

1、使用到的js编程

var process_request = "<img src=‘loading.gif‘ width=‘16‘ height=‘16‘ border=‘0‘ align=‘absmiddle‘>正在数据处理中...";
var username_empty = "<span style=‘COLOR:#ff0000‘>  × 用户名不能为空!</span>";
var username_shorter = "<span style=‘COLOR:#ff0000‘> × 用户名长度不能少于 3 个字符。</span>";
var username_longer = "<span style=‘COLOR:#ff0000‘> × 用户名长度不能大于 30个字符。</span>";
var username_invalid = "- 用户名只能是由字母数字以及下划线组成。";
var username_have_register = "<span style=‘COLOR:#ff0000‘> × 用户名已经存在,请重新输入!</span>";
var username_can_register="<span style=‘COLOR:#006600‘> √ 恭喜您!该用户名可以注册!</span>";
var password_empty = "<span style=‘COLOR:#ff0000‘> × 登录密码不能为空。</span>";
var password_shorter_s = "<span style=‘COLOR:#ff0000‘> × 登录密码不能少于 6 个字符。</span>";
var password_shorter_m = "<span style=‘COLOR:#ff0000‘> × 登录密码不能多于 30 个字符。</span>";
var confirm_password_invalid = "<span style=‘COLOR:#ff0000‘> × 两次输入密码不一致!</span>";
var email_empty = "<span style=‘COLOR:#ff0000‘> × 邮箱不能为空!</span>";
var email_invalid = "<span style=‘COLOR:#ff0000‘> × 邮箱格式出错!</span>";
var email_have_register = "<span style=‘COLOR:#ff0000‘> × 该邮箱已被注册! </span>";
var email_can_register = "<span style=‘COLOR:#006600‘> √ 邮箱可以注册!</span>";
var agreement_no = "<span style=‘COLOR:#ff0000‘> × 您没有接受协议</span>";
var agreement_yes= "<span style=‘COLOR:#006600‘> √ 已经接受协议</span>";
var info_can="<span style=‘COLOR:#006600‘> √ 可以注册!</span>";
var info_right="<span style=‘COLOR:#006600‘> √ 填写正确!</span>";
var name_flag=false;
var email_flag=false;
var password_flag=false;
var accept_flag=false;

$(function(){
	change_submit();
	if(document.getElementById("agreement").checked){
	    alert("checkbox is checked");
	}
}); 

/*
 * 获取工程的路径
 */
function getRootPath() {
	var pathName = window.location.pathname.substring(1);
	var webName = pathName == ‘‘ ? ‘‘ : pathName.substring(0, pathName
			.indexOf(‘/‘));
	return window.location.protocol + ‘//‘ + window.location.host + ‘/‘
			+ webName + ‘/‘;
}
/*
 * 用户名检测
 */
function checkUserName(obj) {
	if (checks(obj.value) == false) {
		showInfo("username_notice", username_invalid);
	} else if (obj.value.length < 1) {
		showInfo("username_notice", username_empty);
	}else if (obj.value.length < 3) {
		showInfo("username_notice", username_shorter);
	} else if(obj.value.length>30){
		showInfo("username_notice", username_longer);
    }else {
		// 调用Ajax函数,向服务器端发送查询
        $.ajax({ //一个Ajax过程
    		type: "post", //以post方式与后台沟通
    		url :getRootPath()+"/register/checkUserName", //与此页面沟通
    		dataType:‘json‘,//返回的值以 JSON方式 解释
    		data: ‘userName=‘+obj.value, //发给的数据
    		success: function(json){//如果调用成功
    			if(json.flag){
    				showInfo("username_notice", username_have_register);
    			}else {
    				showInfo("username_notice", username_can_register);
    				name_flag=true;
    				change_submit();
    				return;
    			}
    		}
    });
	}
	name_flag=false;
	change_submit();
}
/*
 * 用户名检测是否包含非法字符
 */
function checks(t) {
	szMsg = "[#%&\‘\"\\,;:=!^@]"
	for (i = 1; i < szMsg.length + 1; i++) {
		if (t.indexOf(szMsg.substring(i - 1, i)) > -1) {
			return false;
		}
	}
	return true;
}
/*
 * 邮箱检测
 */
 function checkEmail(email) {
	var re = /^(\w-*\.*)[email protected](\w-?)+(\.\w{2,})+$/
	if (email.value.length < 1) {
		showInfo("email_notice", email_empty);
	} else if (!re.test(email.value)) {
		email.className = "FrameDivWarn";
		showInfo("email_notice", email_invalid);
	} else {
		// 调用Ajax函数,向服务器端发送查询
       $.ajax({ //一个Ajax过程
    		type: "post", //以post方式与后台沟通
    		url :getRootPath()+"/register/checkEmail", //与此页面沟通
    		dataType:‘json‘,//返回的值以 JSON方式 解释
    		data: ‘email=‘+email.value, //发给的数据
    		success: function(json){//如果调用成功
    			if(json.flag){
    				showInfo("email_notice", email_have_register);
    			}else {
    				showInfo("email_notice", email_can_register);
    				email_flag=true;
    				change_submit();
    				return;
    			}
    		}
      });
	}
	email_flag=false;
	change_submit();
} 

/*
 * 密码检测
 */
 function checkPassword( password )
 {
	 if(password.value.length < 1){
		 password_flag=false;
         showInfo("password_notice",password_empty);
	 }else if ( password.value.length < 6 )
     {
		 password_flag=false;
         showInfo("password_notice",password_shorter_s);
     }
     else if(password.value.length > 30){
    	 password_flag=false;
         showInfo("password_notice",password_shorter_m);
         }
     else
     {
         showInfo("password_notice",info_right);
     }
	 change_submit();
 }  

 /*
  * 密码确认检测
  */
 function checkConformPassword(conform_password)
 {
	 password = $("#password").val();
	 if (password.length < 1)  {
         showInfo("conform_password_notice",password_empty);  

	 } else if ( conform_password.value!= password)
     {
         showInfo("conform_password_notice",confirm_password_invalid);
     }
     else
     {
         showInfo("conform_password_notice",info_right);
			password_flag=true;
			change_submit();
			return;
     }
	 password_flag=false;
	change_submit();

 }

 /*
  * 检测密码强度检测
  */
 function checkIntensity(pwd)
 {
   var Mcolor = "#FFF",Lcolor = "#FFF",Hcolor = "#FFF";
   var m=0;  

   var Modes = 0;
   for (i=0; i<pwd.length; i++)
   {
     var charType = 0;
     var t = pwd.charCodeAt(i);
     if (t>=48 && t <=57)
     {
       charType = 1;
     }
     else if (t>=65 && t <=90)
     {
       charType = 2;
     }
     else if (t>=97 && t <=122)
       charType = 4;
     else
       charType = 4;
     Modes |= charType;
   }  

   for (i=0;i<4;i++)
   {
     if (Modes & 1) m++;
       Modes>>>=1;
   }  

   if (pwd.length<=4)
   {
     m = 1;
   }  

   switch(m)
   {
     case 1 :
       Lcolor = "2px solid red";
       Mcolor = Hcolor = "2px solid #DADADA";
     break;
     case 2 :
       Mcolor = "2px solid #f90";
       Lcolor = Hcolor = "2px solid #DADADA";
     break;
     case 3 :
       Hcolor = "2px solid #3c0";
       Lcolor = Mcolor = "2px solid #DADADA";
     break;
     case 4 :
       Hcolor = "2px solid #3c0";
       Lcolor = Mcolor = "2px solid #DADADA";
     break;
     default :
       Hcolor = Mcolor = Lcolor = "";
     break;
   }
   document.getElementById("pwd_lower").style.borderBottom  = Lcolor;
   document.getElementById("pwd_middle").style.borderBottom = Mcolor;
   document.getElementById("pwd_high").style.borderBottom   = Hcolor;
 }

//--------------注册协议复选框状态检测---------------------//
 function checkAgreement(obj){
	if(document.getElementById("agreement").checked){
		 showInfo("agreement_notice",agreement_yes);
		accept_flag=true;
		change_submit();
		}else{
		showInfo("agreement_notice",agreement_no);  

		}
/*	 if($("#agreement").attr("checked")=="checked"){
		 alert(‘选中‘);
	 }*/
/*   if (document.formUser.agreement.checked==false)
   {
      showInfo("agreement_notice",checkAgreement);
 } else {
     showInfo("agreement_notice",info_right);
     } */
 }
 /*
  * 按钮状态设置
  */
function change_submit()
{
	if(name_flag&&email_flag&&password_flag&&accept_flag){
		  document.forms[‘formUser‘].elements[‘Submit1‘].disabled = ‘‘;
	}
   else
     {
          document.forms[‘formUser‘].elements[‘Submit1‘].disabled = ‘disabled‘;
     }
}
/*
 * 公用程序
 */
    function showInfo(target,Infos){
    document.getElementById(target).innerHTML = Infos;
    }
    function showclass(target,Infos){
    document.getElementById(target).className = Infos;
    }

2、注册页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.11.3.min.js" ></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/registerCheck.js" ></script>
<title>Ajax+SpringMVC+Spring+MyBatis+Mysql注册验证实例</title>
</head>
<body>
<div id="reg">
<FORM name="formUser"  action="<%=request.getContextPath()%>/register/successed"  method=post>
  <BR>
  <TABLE width="100%" align=center border=0>
    <TBODY>
      <TR>
        <TD align=right width="15%"><STRONG>用户名:</STRONG></TD>
        <TD width="57%"><INPUT id="username" onBlur="checkUserName(this)"
      name="username">
            <SPAN id="username_notice" >*</SPAN></TD>
      </TR>
      <TR>
        <TD align=right><STRONG>邮箱:</STRONG></TD>
        <TD><INPUT id="email" onBlur="checkEmail(this)" name="email">
            <SPAN id=email_notice >*</SPAN></TD>
      </TR>
      <TR>
        <TD align=right><STRONG>密码:</STRONG></TD>
        <TD><INPUT id="password" onBlur="checkPassword(this)"
      onkeyup="checkIntensity(this.value)" type="password" name="password">
            <SPAN
      id=password_notice >*</SPAN></TD>
      </TR>
      <TR>
        <TD align=right><STRONG>密码强度:</STRONG></TD>
        <TD><TABLE cellSpacing=0 cellPadding=1 width=145 border=0>
          <TBODY>
            <TR align=middle>
              <TD id=pwd_lower width="33%">弱</TD>
              <TD id=pwd_middle width="33%">中</TD>
              <TD id=pwd_high width="33%">强</TD>
            </TR>
          </TBODY>
        </TABLE></TD>
      </TR>
      <TR>
        <TD align=right><STRONG>确认密码:</STRONG></TD>
        <TD><INPUT id="conform_password" onBlur="checkConformPassword(this)"
      type="password" name="confirm_password">
            <SPAN id=conform_password_notice >*</SPAN></TD>
      </TR>
      <TR>
        <TD> </TD>
        <TD><LABEL>
          <INPUT type="checkbox" id="agreement" onclick="checkAgreement(this)">
          <B>我已看过并接受《<a href="#">用户协议</a>》<SPAN id=agreement_notice >*</SPAN></B></LABEL></TD>
      </TR>
      <TR>
        <TD  ><INPUT type=hidden value=act_register name=act></TD>
        <TD  ><input type=submit value=确认注册    name="Submit1" class="anniu" disabled></TD>
      </TR>
      <TR>
        <TD colSpan=2> </TD>
      </TR>
    </TBODY>
  </TABLE>
</FORM>
</div>
</body>
</html>

3、注册成功页面

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户注册成功</title>
</head>
<body>
<center>
<h1><b>欢迎新用户</b></h1>
用户名:${requestScope.username}<br>
邮箱:${requestScope.email}<br>
</center>
</body>
</html>

四、Controller编写

使用SpringMVC就得要自己来写Controller,拦截各个请求,处理后再返回给请求者,放在src下的。com.lin.controller

package com.lin.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.lin.domain.User;
import com.lin.domain.UserExample;
import com.lin.domain.UserExample.Criteria;
import com.lin.service.IRegisterService;

@Controller
public class RegisterController {
	private static Logger logger = Logger.getLogger(RegisterController.class);
	@Resource
	private IRegisterService registerService;	

	@RequestMapping({"/register","/"})
	public String register(){
		return "register";
	}
	@RequestMapping(value="/register/checkUserName",method = RequestMethod.POST)
	public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String userName=(String)request.getParameter("userName");
		//检验用户名是否存在
		UserExample userExample=new UserExample();
		Criteria conditionCri = userExample.createCriteria();
		conditionCri.andUserNameEqualTo(userName);
	    int num=registerService.countByExample(userExample);
	    //用户名是否存在的标志
	    boolean flag=false;
	    if(num>0){
	    	flag=true;
	    }
		//将数据转换成json
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("flag", flag);
		String json = JSONObject.fromObject(map).toString();
		//将数据返回
		response.setCharacterEncoding("UTF-8");
		response.flushBuffer();
		response.getWriter().write(json);
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	@RequestMapping(value="/register/checkEmail",method = RequestMethod.POST)
	public String checkEmail(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String email=(String)request.getParameter("email");
		//检验邮箱是否存在
		UserExample userExample=new UserExample();
		Criteria conditionCri = userExample.createCriteria();
		conditionCri.andUserEmailEqualTo(email);
	    int num=registerService.countByExample(userExample);
	    //用户名是否存在的标志
	    boolean flag=false;
	    if(num>0){
	    	flag=true;
	    }
		//将数据转换成json
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("flag", flag);
		String json = JSONObject.fromObject(map).toString();
		//将数据返回
		response.setCharacterEncoding("UTF-8");
		response.flushBuffer();
		response.getWriter().write(json);
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}
	@RequestMapping(value="/register/successed")
	public ModelAndView  successed(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String username=(String)request.getParameter("username");
		String email=(String)request.getParameter("email");
		String password=(String)request.getParameter("password");
		if(username==null||email==null||password==null){
			return new ModelAndView("redirect:/register");
		}
		//新增用户插入数据库
		User user=new User();
		user.setUserName(username);
		user.setUserEmail(email);
		user.setUserPassword(password);
		registerService.insert(user);
		//将数据转换成
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("username", username);
		map.put("email", email);
		map.put("password", password);
/*		String json = JSONObject.fromObject(map).toString();
		//将数据返回
		response.setCharacterEncoding("UTF-8");
		response.flushBuffer();
		response.getWriter().write(json);
		response.getWriter().flush();
		response.getWriter().close();*/
		return new ModelAndView("successed",map);
	}

}

五、结果分析

1、运行

2、然后来看看打印出来的sql语句:

这是要验证用户名:

每次输入后,移开鼠标后就验证,并返回结果

这是在验证邮箱:

3、最后还要看看数据库数据进去了没有:

这是还没注册之前的:

这是数据成功插入之后的”,我做了很多次,所以数据有点多。

本文工程免费下载

版权声明:本文为博主林炳文Evankaka原创文章,未经博主允许不得转载。

时间: 2024-11-06 20:17:45

Ajax+SpringMVC+Spring+Mybatis+MySql+js用户注册实例的相关文章

SpringMVC+Spring+Mybatis+Mysql项目搭建

眼下俺在搭建一个自己的个人站点玩玩.一边练习.一边把用到的技术总结一下,日后好复习. 站点框架大致例如以下图所看到的: 眼下仅仅用到了SpringMVC+Spring+Mybatis+Mysql.把它弄到了自己的server上来玩耍. 后台结构图: 眼下主要分为: view–controller层与前台交互,登陆拦截器 utils–工具类.一些经常使用的工具类. interceptor–拦截器.页面请求地址拦截和预防XSS漏洞拦截. impl–接口类,Service层-进行业务处理. excep

SpringMVC +Spring + MyBatis + Mysql + Redis(作为二级缓存) 配置

转载:http://blog.csdn.net/xiadi934/article/details/50786293 项目环境: 在SpringMVC +Spring + MyBatis + MySQL.Redis部署在Linux虚拟机. 1.整体思路 参考Ehcache实现MyBatis二级缓存代码(Maven引用对应jar查阅) 使用Spring管理Redis连接池 模仿EhcacheCache,实现RedisCache 2.pom.xml中加入Maven依赖 1 <!-- spring-re

springmvc学习总结(二) -- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解

@[email protected] 写在最前 之前分享过下面这几篇: mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)(附demo和搭建过程遇到的问题解决方法) mybatis学习笔记(六) -- maven+spring+mybatis从零开始搭建整合详细过程(下) springmvc学习笔记(一) -- 从零搭建,基础入门 这一篇,在这些练习的基础上,将它们整合在一起! 搭建步骤如下 一.新建maven项目,配置环境,测试是否配置成

springmvc+spring+mybatis+mysql配置过程

环境:eclipse 项目目录: jar包: web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http:/

maven搭建springmvc+spring+mybatis实例

最近做了个maven管理的springmvc+spring+mybatis,还用到了阿里巴巴的 fastjson和druid连接池,配置文件如下 pom.xml文件 [html] view plaincopy <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http:

课程分享】基于Springmvc+Spring+Mybatis+Bootstrap+jQuery Mobile +MySql教务管理系统

课程讲师:老牛 课程分类:Java框架 适合人群:初级 课时数量:85课时 更新程度:完成 用到技术:Springmvc+Spring+Mybatis+Bootstrap+jQueryMobile 涉及项目:PC端和手机端教务管理系统 需要更多相关资料可以联系 Q2748165793 课程大纲 技能储备 第1课springMVC概述和基础配置 第2课springMVC注解和参数传递 第3课springMVC和JSON数据 第4课springMVC上传下载 第5课springMVC 与 sprin

Idea SpringMVC+Spring+MyBatis+Maven调整【转】

Idea SpringMVC+Spring+MyBatis+Maven整合 创建项目 File-New Project 选中左侧的Maven,选中右侧上方的Create from archetype,然后选中下方列表中的webapp,然后点击Next 在GroupId和ArtifactId中填入指定内容,点击Next 直接点Next 输入项目名称,Finish Idea会自动开始下载所依赖的包,等待其完成. 项目结构 项目刚建好的时候是没有这些文件的,所以自己手动创建缺少的文件夹(包) 创建完后

SpringMVC+Spring+Mybatis(SSM~Demo) 【转】

SpringMVC+Spring+Mybatis 框架搭建 整个Demo的视图结构: JAR: 下载地址:http://download.csdn.net/detail/li1669852599/8546059 首先,我是使用MyEclipse工具做的这个例子,整合了Sping 3 .Spring MVC 3 .MyBatis框架,演示数据库采用MySQL数据库.例子中主要操作包括对数据的添加(C).查找(R).更新(U).删除(D).我在这里采用的数据库连接池是来自阿里巴巴的Druid,至于D

springmvc+spring+mybatis+maven项目构建

1.首先在myeclipse10中安装maven的插件,将插件放入D:\Program Files (x86)\myEclipse10\MyEclipse Blue Edition 10\dropins\maven中, 2. 新建文件:maven.link填入如下内容:path=D:/Program Files (x86)/myEclipse10/MyEclipse Blue Edition 10/dropins/maven 3.重启myeclipse插件安装成功. 4.在myeclipse10