27、SSH框架-Ajax+SpringMVC+Spring+Mybatis+MySql+js用户注册实例(2)

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

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

本文工程免费下载

先来看看最终效果:

注册成功的样子:


注册过程中参数的检验:


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

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

  1. CREATE TABLE  
  2.     t_user  
  3.     (  
  4.         USER_ID INT NOT NULL AUTO_INCREMENT,  
  5.         USER_NAME CHAR(30) NOT NULL,  
  6.         USER_PASSWORD CHAR(10) NOT NULL,  
  7.         USER_EMAIL CHAR(30) NOT NULL,  
  8.         PRIMARY KEY (USER_ID)  
  9.     )  
  10.     ENGINE=InnoDB DEFAULT CHARSET=utf8;  
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

  1. package com.lin.domain;  
  2.   
  3. public class User {  
  4.     /** 
  5.      * This field was generated by MyBatis Generator. 
  6.      * This field corresponds to the database column t_user.USER_ID 
  7.      * 
  8.      * @mbggenerated 
  9.      */  
  10.     private Integer userId;  
  11.   
  12.     /** 
  13.      * This field was generated by MyBatis Generator. 
  14.      * This field corresponds to the database column t_user.USER_NAME 
  15.      * 
  16.      * @mbggenerated 
  17.      */  
  18.     private String userName;  
  19.   
  20.     /** 
  21.      * This field was generated by MyBatis Generator. 
  22.      * This field corresponds to the database column t_user.USER_PASSWORD 
  23.      * 
  24.      * @mbggenerated 
  25.      */  
  26.     private String userPassword;  
  27.   
  28.     /** 
  29.      * This field was generated by MyBatis Generator. 
  30.      * This field corresponds to the database column t_user.USER_EMAIL 
  31.      * 
  32.      * @mbggenerated 
  33.      */  
  34.     private String userEmail;  
  35.   
  36.     /** 
  37.      * This method was generated by MyBatis Generator. 
  38.      * This method returns the value of the database column t_user.USER_ID 
  39.      * 
  40.      * @return the value of t_user.USER_ID 
  41.      * 
  42.      * @mbggenerated 
  43.      */  
  44.     public Integer getUserId() {  
  45.         return userId;  
  46.     }  
  47.   
  48.     /** 
  49.      * This method was generated by MyBatis Generator. 
  50.      * This method sets the value of the database column t_user.USER_ID 
  51.      * 
  52.      * @param userId the value for t_user.USER_ID 
  53.      * 
  54.      * @mbggenerated 
  55.      */  
  56.     public void setUserId(Integer userId) {  
  57.         this.userId = userId;  
  58.     }  
  59.   
  60.     /** 
  61.      * This method was generated by MyBatis Generator. 
  62.      * This method returns the value of the database column t_user.USER_NAME 
  63.      * 
  64.      * @return the value of t_user.USER_NAME 
  65.      * 
  66.      * @mbggenerated 
  67.      */  
  68.     public String getUserName() {  
  69.         return userName;  
  70.     }  
  71.   
  72.     /** 
  73.      * This method was generated by MyBatis Generator. 
  74.      * This method sets the value of the database column t_user.USER_NAME 
  75.      * 
  76.      * @param userName the value for t_user.USER_NAME 
  77.      * 
  78.      * @mbggenerated 
  79.      */  
  80.     public void setUserName(String userName) {  
  81.         this.userName = userName == null ? null : userName.trim();  
  82.     }  
  83.   
  84.     /** 
  85.      * This method was generated by MyBatis Generator. 
  86.      * This method returns the value of the database column t_user.USER_PASSWORD 
  87.      * 
  88.      * @return the value of t_user.USER_PASSWORD 
  89.      * 
  90.      * @mbggenerated 
  91.      */  
  92.     public String getUserPassword() {  
  93.         return userPassword;  
  94.     }  
  95.   
  96.     /** 
  97.      * This method was generated by MyBatis Generator. 
  98.      * This method sets the value of the database column t_user.USER_PASSWORD 
  99.      * 
  100.      * @param userPassword the value for t_user.USER_PASSWORD 
  101.      * 
  102.      * @mbggenerated 
  103.      */  
  104.     public void setUserPassword(String userPassword) {  
  105.         this.userPassword = userPassword == null ? null : userPassword.trim();  
  106.     }  
  107.   
  108.     /** 
  109.      * This method was generated by MyBatis Generator. 
  110.      * This method returns the value of the database column t_user.USER_EMAIL 
  111.      * 
  112.      * @return the value of t_user.USER_EMAIL 
  113.      * 
  114.      * @mbggenerated 
  115.      */  
  116.     public String getUserEmail() {  
  117.         return userEmail;  
  118.     }  
  119.   
  120.     /** 
  121.      * This method was generated by MyBatis Generator. 
  122.      * This method sets the value of the database column t_user.USER_EMAIL 
  123.      * 
  124.      * @param userEmail the value for t_user.USER_EMAIL 
  125.      * 
  126.      * @mbggenerated 
  127.      */  
  128.     public void setUserEmail(String userEmail) {  
  129.         this.userEmail = userEmail == null ? null : userEmail.trim();  
  130.     }  
  131. }  
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

  1. package com.lin.domain;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. public class UserExample {  
  7.     /** 
  8.      * This field was generated by MyBatis Generator. 
  9.      * This field corresponds to the database table t_user 
  10.      * 
  11.      * @mbggenerated 
  12.      */  
  13.     protected String orderByClause;  
  14.   
  15.     /** 
  16.      * This field was generated by MyBatis Generator. 
  17.      * This field corresponds to the database table t_user 
  18.      * 
  19.      * @mbggenerated 
  20.      */  
  21.     protected boolean distinct;  
  22.   
  23.     /** 
  24.      * This field was generated by MyBatis Generator. 
  25.      * This field corresponds to the database table t_user 
  26.      * 
  27.      * @mbggenerated 
  28.      */  
  29.     protected List<Criteria> oredCriteria;  
  30.   
  31.     /** 
  32.      * This method was generated by MyBatis Generator. 
  33.      * This method corresponds to the database table t_user 
  34.      * 
  35.      * @mbggenerated 
  36.      */  
  37.     public UserExample() {  
  38.         oredCriteria = new ArrayList<Criteria>();  
  39.     }  
  40.   
  41.     /** 
  42.      * This method was generated by MyBatis Generator. 
  43.      * This method corresponds to the database table t_user 
  44.      * 
  45.      * @mbggenerated 
  46.      */  
  47.     public void setOrderByClause(String orderByClause) {  
  48.         this.orderByClause = orderByClause;  
  49.     }  
  50.   
  51.     /** 
  52.      * This method was generated by MyBatis Generator. 
  53.      * This method corresponds to the database table t_user 
  54.      * 
  55.      * @mbggenerated 
  56.      */  
  57.     public String getOrderByClause() {  
  58.         return orderByClause;  
  59.     }  
  60.   
  61.     /** 
  62.      * This method was generated by MyBatis Generator. 
  63.      * This method corresponds to the database table t_user 
  64.      * 
  65.      * @mbggenerated 
  66.      */  
  67.     public void setDistinct(boolean distinct) {  
  68.         this.distinct = distinct;  
  69.     }  
  70.   
  71.     /** 
  72.      * This method was generated by MyBatis Generator. 
  73.      * This method corresponds to the database table t_user 
  74.      * 
  75.      * @mbggenerated 
  76.      */  
  77.     public boolean isDistinct() {  
  78.         return distinct;  
  79.     }  
  80.   
  81.     /** 
  82.      * This method was generated by MyBatis Generator. 
  83.      * This method corresponds to the database table t_user 
  84.      * 
  85.      * @mbggenerated 
  86.      */  
  87.     public List<Criteria> getOredCriteria() {  
  88.         return oredCriteria;  
  89.     }  
  90.   
  91.     /** 
  92.      * This method was generated by MyBatis Generator. 
  93.      * This method corresponds to the database table t_user 
  94.      * 
  95.      * @mbggenerated 
  96.      */  
  97.     public void or(Criteria criteria) {  
  98.         oredCriteria.add(criteria);  
  99.     }  
  100.   
  101.     /** 
  102.      * This method was generated by MyBatis Generator. 
  103.      * This method corresponds to the database table t_user 
  104.      * 
  105.      * @mbggenerated 
  106.      */  
  107.     public Criteria or() {  
  108.         Criteria criteria = createCriteriaInternal();  
  109.         oredCriteria.add(criteria);  
  110.         return criteria;  
  111.     }  
  112.   
  113.     /** 
  114.      * This method was generated by MyBatis Generator. 
  115.      * This method corresponds to the database table t_user 
  116.      * 
  117.      * @mbggenerated 
  118.      */  
  119.     public Criteria createCriteria() {  
  120.         Criteria criteria = createCriteriaInternal();  
  121.         if (oredCriteria.size() == 0) {  
  122.             oredCriteria.add(criteria);  
  123.         }  
  124.         return criteria;  
  125.     }  
  126.   
  127.     /** 
  128.      * This method was generated by MyBatis Generator. 
  129.      * This method corresponds to the database table t_user 
  130.      * 
  131.      * @mbggenerated 
  132.      */  
  133.     protected Criteria createCriteriaInternal() {  
  134.         Criteria criteria = new Criteria();  
  135.         return criteria;  
  136.     }  
  137.   
  138.     /** 
  139.      * This method was generated by MyBatis Generator. 
  140.      * This method corresponds to the database table t_user 
  141.      * 
  142.      * @mbggenerated 
  143.      */  
  144.     public void clear() {  
  145.         oredCriteria.clear();  
  146.         orderByClause = null;  
  147.         distinct = false;  
  148.     }  
  149.   
  150.     /** 
  151.      * This class was generated by MyBatis Generator. 
  152.      * This class corresponds to the database table t_user 
  153.      * 
  154.      * @mbggenerated 
  155.      */  
  156.     protected abstract static class GeneratedCriteria {  
  157.         protected List<Criterion> criteria;  
  158.   
  159.         protected GeneratedCriteria() {  
  160.             super();  
  161.             criteria = new ArrayList<Criterion>();  
  162.         }  
  163.   
  164.         public boolean isValid() {  
  165.             return criteria.size() > 0;  
  166.         }  
  167.   
  168.         public List<Criterion> getCriteria() {  
  169.             return criteria;  
  170.         }  
  171.   
  172.         protected void addCriterion(String condition) {  
  173.             if (condition == null) {  
  174.                 throw new RuntimeException("Value for condition cannot be null");  
  175.             }  
  176.             criteria.add(new Criterion(condition));  
  177.         }  
  178.   
  179.         protected void addCriterion(String condition, Object value, String property) {  
  180.             if (value == null) {  
  181.                 throw new RuntimeException("Value for " + property + " cannot be null");  
  182.             }  
  183.             criteria.add(new Criterion(condition, value));  
  184.         }  
  185.   
  186.         protected void addCriterion(String condition, Object value1, Object value2, String property) {  
  187.             if (value1 == null || value2 == null) {  
  188.                 throw new RuntimeException("Between values for " + property + " cannot be null");  
  189.             }  
  190.             criteria.add(new Criterion(condition, value1, value2));  
  191.         }  
  192.   
  193.         public Criteria andUserIdIsNull() {  
  194.             addCriterion("USER_ID is null");  
  195.             return (Criteria) this;  
  196.         }  
  197.   
  198.         public Criteria andUserIdIsNotNull() {  
  199.             addCriterion("USER_ID is not null");  
  200.             return (Criteria) this;  
  201.         }  
  202.   
  203.         public Criteria andUserIdEqualTo(Integer value) {  
  204.             addCriterion("USER_ID =", value, "userId");  
  205.             return (Criteria) this;  
  206.         }  
  207.   
  208.         public Criteria andUserIdNotEqualTo(Integer value) {  
  209.             addCriterion("USER_ID <>", value, "userId");  
  210.             return (Criteria) this;  
  211.         }  
  212.   
  213.         public Criteria andUserIdGreaterThan(Integer value) {  
  214.             addCriterion("USER_ID >", value, "userId");  
  215.             return (Criteria) this;  
  216.         }  
  217.   
  218.         public Criteria andUserIdGreaterThanOrEqualTo(Integer value) {  
  219.             addCriterion("USER_ID >=", value, "userId");  
  220.             return (Criteria) this;  
  221.         }  
  222.   
  223.         public Criteria andUserIdLessThan(Integer value) {  
  224.             addCriterion("USER_ID <", value, "userId");  
  225.             return (Criteria) this;  
  226.         }  
  227.   
  228.         public Criteria andUserIdLessThanOrEqualTo(Integer value) {  
  229.             addCriterion("USER_ID <=", value, "userId");  
  230.             return (Criteria) this;  
  231.         }  
  232.   
  233.         public Criteria andUserIdIn(List<Integer> values) {  
  234.             addCriterion("USER_ID in", values, "userId");  
  235.             return (Criteria) this;  
  236.         }  
  237.   
  238.         public Criteria andUserIdNotIn(List<Integer> values) {  
  239.             addCriterion("USER_ID not in", values, "userId");  
  240.             return (Criteria) this;  
  241.         }  
  242.   
  243.         public Criteria andUserIdBetween(Integer value1, Integer value2) {  
  244.             addCriterion("USER_ID between", value1, value2, "userId");  
  245.             return (Criteria) this;  
  246.         }  
  247.   
  248.         public Criteria andUserIdNotBetween(Integer value1, Integer value2) {  
  249.             addCriterion("USER_ID not between", value1, value2, "userId");  
  250.             return (Criteria) this;  
  251.         }  
  252.   
  253.         public Criteria andUserNameIsNull() {  
  254.             addCriterion("USER_NAME is null");  
  255.             return (Criteria) this;  
  256.         }  
  257.   
  258.         public Criteria andUserNameIsNotNull() {  
  259.             addCriterion("USER_NAME is not null");  
  260.             return (Criteria) this;  
  261.         }  
  262.   
  263.         public Criteria andUserNameEqualTo(String value) {  
  264.             addCriterion("USER_NAME =", value, "userName");  
  265.             return (Criteria) this;  
  266.         }  
  267.   
  268.         public Criteria andUserNameNotEqualTo(String value) {  
  269.             addCriterion("USER_NAME <>", value, "userName");  
  270.             return (Criteria) this;  
  271.         }  
  272.   
  273.         public Criteria andUserNameGreaterThan(String value) {  
  274.             addCriterion("USER_NAME >", value, "userName");  
  275.             return (Criteria) this;  
  276.         }  
  277.   
  278.         public Criteria andUserNameGreaterThanOrEqualTo(String value) {  
  279.             addCriterion("USER_NAME >=", value, "userName");  
  280.             return (Criteria) this;  
  281.         }  
  282.   
  283.         public Criteria andUserNameLessThan(String value) {  
  284.             addCriterion("USER_NAME <", value, "userName");  
  285.             return (Criteria) this;  
  286.         }  
  287.   
  288.         public Criteria andUserNameLessThanOrEqualTo(String value) {  
  289.             addCriterion("USER_NAME <=", value, "userName");  
  290.             return (Criteria) this;  
  291.         }  
  292.   
  293.         public Criteria andUserNameLike(String value) {  
  294.             addCriterion("USER_NAME like", value, "userName");  
  295.             return (Criteria) this;  
  296.         }  
  297.   
  298.         public Criteria andUserNameNotLike(String value) {  
  299.             addCriterion("USER_NAME not like", value, "userName");  
  300.             return (Criteria) this;  
  301.         }  
  302.   
  303.         public Criteria andUserNameIn(List<String> values) {  
  304.             addCriterion("USER_NAME in", values, "userName");  
  305.             return (Criteria) this;  
  306.         }  
  307.   
  308.         public Criteria andUserNameNotIn(List<String> values) {  
  309.             addCriterion("USER_NAME not in", values, "userName");  
  310.             return (Criteria) this;  
  311.         }  
  312.   
  313.         public Criteria andUserNameBetween(String value1, String value2) {  
  314.             addCriterion("USER_NAME between", value1, value2, "userName");  
  315.             return (Criteria) this;  
  316.         }  
  317.   
  318.         public Criteria andUserNameNotBetween(String value1, String value2) {  
  319.             addCriterion("USER_NAME not between", value1, value2, "userName");  
  320.             return (Criteria) this;  
  321.         }  
  322.   
  323.         public Criteria andUserPasswordIsNull() {  
  324.             addCriterion("USER_PASSWORD is null");  
  325.             return (Criteria) this;  
  326.         }  
  327.   
  328.         public Criteria andUserPasswordIsNotNull() {  
  329.             addCriterion("USER_PASSWORD is not null");  
  330.             return (Criteria) this;  
  331.         }  
  332.   
  333.         public Criteria andUserPasswordEqualTo(String value) {  
  334.             addCriterion("USER_PASSWORD =", value, "userPassword");  
  335.             return (Criteria) this;  
  336.         }  
  337.   
  338.         public Criteria andUserPasswordNotEqualTo(String value) {  
  339.             addCriterion("USER_PASSWORD <>", value, "userPassword");  
  340.             return (Criteria) this;  
  341.         }  
  342.   
  343.         public Criteria andUserPasswordGreaterThan(String value) {  
  344.             addCriterion("USER_PASSWORD >", value, "userPassword");  
  345.             return (Criteria) this;  
  346.         }  
  347.   
  348.         public Criteria andUserPasswordGreaterThanOrEqualTo(String value) {  
  349.             addCriterion("USER_PASSWORD >=", value, "userPassword");  
  350.             return (Criteria) this;  
  351.         }  
  352.   
  353.         public Criteria andUserPasswordLessThan(String value) {  
  354.             addCriterion("USER_PASSWORD <", value, "userPassword");  
  355.             return (Criteria) this;  
  356.         }  
  357.   
  358.         public Criteria andUserPasswordLessThanOrEqualTo(String value) {  
  359.             addCriterion("USER_PASSWORD <=", value, "userPassword");  
  360.             return (Criteria) this;  
  361.         }  
  362.   
  363.         public Criteria andUserPasswordLike(String value) {  
  364.             addCriterion("USER_PASSWORD like", value, "userPassword");  
  365.             return (Criteria) this;  
  366.         }  
  367.   
  368.         public Criteria andUserPasswordNotLike(String value) {  
  369.             addCriterion("USER_PASSWORD not like", value, "userPassword");  
  370.             return (Criteria) this;  
  371.         }  
  372.   
  373.         public Criteria andUserPasswordIn(List<String> values) {  
  374.             addCriterion("USER_PASSWORD in", values, "userPassword");  
  375.             return (Criteria) this;  
  376.         }  
  377.   
  378.         public Criteria andUserPasswordNotIn(List<String> values) {  
  379.             addCriterion("USER_PASSWORD not in", values, "userPassword");  
  380.             return (Criteria) this;  
  381.         }  
  382.   
  383.         public Criteria andUserPasswordBetween(String value1, String value2) {  
  384.             addCriterion("USER_PASSWORD between", value1, value2, "userPassword");  
  385.             return (Criteria) this;  
  386.         }  
  387.   
  388.         public Criteria andUserPasswordNotBetween(String value1, String value2) {  
  389.             addCriterion("USER_PASSWORD not between", value1, value2, "userPassword");  
  390.             return (Criteria) this;  
  391.         }  
  392.   
  393.         public Criteria andUserEmailIsNull() {  
  394.             addCriterion("USER_EMAIL is null");  
  395.             return (Criteria) this;  
  396.         }  
  397.   
  398.         public Criteria andUserEmailIsNotNull() {  
  399.             addCriterion("USER_EMAIL is not null");  
  400.             return (Criteria) this;  
  401.         }  
  402.   
  403.         public Criteria andUserEmailEqualTo(String value) {  
  404.             addCriterion("USER_EMAIL =", value, "userEmail");  
  405.             return (Criteria) this;  
  406.         }  
  407.   
  408.         public Criteria andUserEmailNotEqualTo(String value) {  
  409.             addCriterion("USER_EMAIL <>", value, "userEmail");  
  410.             return (Criteria) this;  
  411.         }  
  412.   
  413.         public Criteria andUserEmailGreaterThan(String value) {  
  414.             addCriterion("USER_EMAIL >", value, "userEmail");  
  415.             return (Criteria) this;  
  416.         }  
  417.   
  418.         public Criteria andUserEmailGreaterThanOrEqualTo(String value) {  
  419.             addCriterion("USER_EMAIL >=", value, "userEmail");  
  420.             return (Criteria) this;  
  421.         }  
  422.   
  423.         public Criteria andUserEmailLessThan(String value) {  
  424.             addCriterion("USER_EMAIL <", value, "userEmail");  
  425.             return (Criteria) this;  
  426.         }  
  427.   
  428.         public Criteria andUserEmailLessThanOrEqualTo(String value) {  
  429.             addCriterion("USER_EMAIL <=", value, "userEmail");  
  430.             return (Criteria) this;  
  431.         }  
  432.   
  433.         public Criteria andUserEmailLike(String value) {  
  434.             addCriterion("USER_EMAIL like", value, "userEmail");  
  435.             return (Criteria) this;  
  436.         }  
  437.   
  438.         public Criteria andUserEmailNotLike(String value) {  
  439.             addCriterion("USER_EMAIL not like", value, "userEmail");  
  440.             return (Criteria) this;  
  441.         }  
  442.   
  443.         public Criteria andUserEmailIn(List<String> values) {  
  444.             addCriterion("USER_EMAIL in", values, "userEmail");  
  445.             return (Criteria) this;  
  446.         }  
  447.   
  448.         public Criteria andUserEmailNotIn(List<String> values) {  
  449.             addCriterion("USER_EMAIL not in", values, "userEmail");  
  450.             return (Criteria) this;  
  451.         }  
  452.   
  453.         public Criteria andUserEmailBetween(String value1, String value2) {  
  454.             addCriterion("USER_EMAIL between", value1, value2, "userEmail");  
  455.             return (Criteria) this;  
  456.         }  
  457.   
  458.         public Criteria andUserEmailNotBetween(String value1, String value2) {  
  459.             addCriterion("USER_EMAIL not between", value1, value2, "userEmail");  
  460.             return (Criteria) this;  
  461.         }  
  462.     }  
  463.   
  464.     /** 
  465.      * This class was generated by MyBatis Generator. 
  466.      * This class corresponds to the database table t_user 
  467.      * 
  468.      * @mbggenerated do_not_delete_during_merge 
  469.      */  
  470.     public static class Criteria extends GeneratedCriteria {  
  471.   
  472.         protected Criteria() {  
  473.             super();  
  474.         }  
  475.     }  
  476.   
  477.     /** 
  478.      * This class was generated by MyBatis Generator. 
  479.      * This class corresponds to the database table t_user 
  480.      * 
  481.      * @mbggenerated 
  482.      */  
  483.     public static class Criterion {  
  484.         private String condition;  
  485.   
  486.         private Object value;  
  487.   
  488.         private Object secondValue;  
  489.   
  490.         private boolean noValue;  
  491.   
  492.         private boolean singleValue;  
  493.   
  494.         private boolean betweenValue;  
  495.   
  496.         private boolean listValue;  
  497.   
  498.         public String getCondition() {  
  499.             return condition;  
  500.         }  
  501.   
  502.         public Object getValue() {  
  503.             return value;  
  504.         }  
  505.   
  506.         public Object getSecondValue() {  
  507.             return secondValue;  
  508.         }  
  509.   
  510.         public boolean isNoValue() {  
  511.             return noValue;  
  512.         }  
  513.   
  514.         public boolean isSingleValue() {  
  515.             return singleValue;  
  516.         }  
  517.   
  518.         public boolean isBetweenValue() {  
  519.             return betweenValue;  
  520.         }  
  521.   
  522.         public boolean isListValue() {  
  523.             return listValue;  
  524.         }  
  525.   
  526.         protected Criterion(String condition) {  
  527.             super();  
  528.             this.condition = condition;  
  529.             this.noValue = true;  
  530.         }  
  531.   
  532.         protected Criterion(String condition, Object value) {  
  533.             super();  
  534.             this.condition = condition;  
  535.             this.value = value;  
  536.             if (value instanceof List<?>) {  
  537.                 this.listValue = true;  
  538.             } else {  
  539.                 this.singleValue = true;  
  540.             }  
  541.         }  
  542.   
  543.         protected Criterion(String condition, Object value, Object secondValue) {  
  544.             super();  
  545.             this.condition = condition;  
  546.             this.value = value;  
  547.             this.secondValue = secondValue;  
  548.             this.betweenValue = true;  
  549.         }  
  550.     }  
  551. }  
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

  1. package com.lin.dao;  
  2.   
  3. import com.lin.domain.User;  
  4. import com.lin.domain.UserExample;  
  5. import java.util.List;  
  6. import org.apache.ibatis.annotations.Param;  
  7.   
  8. public interface UserDao {  
  9.     /** 
  10.      * This method was generated by MyBatis Generator. 
  11.      * This method corresponds to the database table t_user 
  12.      * 
  13.      * @mbggenerated 
  14.      */  
  15.     int countByExample(UserExample example);  
  16.   
  17.     /** 
  18.      * This method was generated by MyBatis Generator. 
  19.      * This method corresponds to the database table t_user 
  20.      * 
  21.      * @mbggenerated 
  22.      */  
  23.     int deleteByExample(UserExample example);  
  24.   
  25.     /** 
  26.      * This method was generated by MyBatis Generator. 
  27.      * This method corresponds to the database table t_user 
  28.      * 
  29.      * @mbggenerated 
  30.      */  
  31.     int deleteByPrimaryKey(Integer userId);  
  32.   
  33.     /** 
  34.      * This method was generated by MyBatis Generator. 
  35.      * This method corresponds to the database table t_user 
  36.      * 
  37.      * @mbggenerated 
  38.      */  
  39.     int insert(User record);  
  40.   
  41.     /** 
  42.      * This method was generated by MyBatis Generator. 
  43.      * This method corresponds to the database table t_user 
  44.      * 
  45.      * @mbggenerated 
  46.      */  
  47.     int insertSelective(User record);  
  48.   
  49.     /** 
  50.      * This method was generated by MyBatis Generator. 
  51.      * This method corresponds to the database table t_user 
  52.      * 
  53.      * @mbggenerated 
  54.      */  
  55.     List<User> selectByExample(UserExample example);  
  56.   
  57.     /** 
  58.      * This method was generated by MyBatis Generator. 
  59.      * This method corresponds to the database table t_user 
  60.      * 
  61.      * @mbggenerated 
  62.      */  
  63.     User selectByPrimaryKey(Integer userId);  
  64.   
  65.     /** 
  66.      * This method was generated by MyBatis Generator. 
  67.      * This method corresponds to the database table t_user 
  68.      * 
  69.      * @mbggenerated 
  70.      */  
  71.     int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);  
  72.   
  73.     /** 
  74.      * This method was generated by MyBatis Generator. 
  75.      * This method corresponds to the database table t_user 
  76.      * 
  77.      * @mbggenerated 
  78.      */  
  79.     int updateByExample(@Param("record") User record, @Param("example") UserExample example);  
  80.   
  81.     /** 
  82.      * This method was generated by MyBatis Generator. 
  83.      * This method corresponds to the database table t_user 
  84.      * 
  85.      * @mbggenerated 
  86.      */  
  87.     int updateByPrimaryKeySelective(User record);  
  88.   
  89.     /** 
  90.      * This method was generated by MyBatis Generator. 
  91.      * This method corresponds to the database table t_user 
  92.      * 
  93.      * @mbggenerated 
  94.      */  
  95.     int updateByPrimaryKey(User record);  
  96. }  
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层

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

接口类:

  1. package com.lin.service;  
  2.   
  3. import com.lin.domain.User;  
  4. import com.lin.domain.UserExample;  
  5.   
  6. public interface IRegisterService {  
  7.       
  8.     public int insert(User record);  
  9.       
  10.     public int countByExample(UserExample example);  
  11.   
  12. }  
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);

}

实现类:

  1. package com.lin.service.impl;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.apache.log4j.Logger;  
  6. import org.springframework.stereotype.Service;  
  7.   
  8. import com.lin.dao.UserDao;  
  9. import com.lin.domain.User;  
  10. import com.lin.domain.UserExample;  
  11. import com.lin.service.IRegisterService;  
  12. @Service("registerService")  
  13. public class RegisterServiceImpl implements IRegisterService{  
  14.     private static Logger logger = Logger.getLogger(RegisterServiceImpl.class);    
  15.     @Resource  
  16.     private UserDao userDao;  
  17.   
  18.     @Override  
  19.     public int insert(User record) {      
  20.         try {  
  21.             return userDao.insert(record);  
  22.         } catch (Exception e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.         return 0;  
  26.     }  
  27.   
  28.     @Override  
  29.     public int countByExample(UserExample example) {  
  30.         try {  
  31.             return userDao.countByExample(example);  
  32.         } catch (Exception e) {  
  33.             e.printStackTrace();  
  34.         }  
  35.         return 0;  
  36.     }  
  37.   
  38. }  
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包下

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="com.lin.dao.UserDao">  
  4.   <resultMap id="BaseResultMap" type="com.lin.domain.User">  
  5.     <!--  
  6.       WARNING - @mbggenerated  
  7.       This element is automatically generated by MyBatis Generator, do not modify.  
  8.     -->  
  9.     <id column="USER_ID" jdbcType="INTEGER" property="userId" />  
  10.     <result column="USER_NAME" jdbcType="CHAR" property="userName" />  
  11.     <result column="USER_PASSWORD" jdbcType="CHAR" property="userPassword" />  
  12.     <result column="USER_EMAIL" jdbcType="CHAR" property="userEmail" />  
  13.   </resultMap>  
  14.   <sql id="Example_Where_Clause">  
  15.     <!--  
  16.       WARNING - @mbggenerated  
  17.       This element is automatically generated by MyBatis Generator, do not modify.  
  18.     -->  
  19.     <where>  
  20.       <foreach collection="oredCriteria" item="criteria" separator="or">  
  21.         <if test="criteria.valid">  
  22.           <trim prefix="(" prefixOverrides="and" suffix=")">  
  23.             <foreach collection="criteria.criteria" item="criterion">  
  24.               <choose>  
  25.                 <when test="criterion.noValue">  
  26.                   and ${criterion.condition}  
  27.                 </when>  
  28.                 <when test="criterion.singleValue">  
  29.                   and ${criterion.condition} #{criterion.value}  
  30.                 </when>  
  31.                 <when test="criterion.betweenValue">  
  32.                   and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}  
  33.                 </when>  
  34.                 <when test="criterion.listValue">  
  35.                   and ${criterion.condition}  
  36.                   <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">  
  37.                     #{listItem}  
  38.                   </foreach>  
  39.                 </when>  
  40.               </choose>  
  41.             </foreach>  
  42.           </trim>  
  43.         </if>  
  44.       </foreach>  
  45.     </where>  
  46.   </sql>  
  47.   <sql id="Update_By_Example_Where_Clause">  
  48.     <!--  
  49.       WARNING - @mbggenerated  
  50.       This element is automatically generated by MyBatis Generator, do not modify.  
  51.     -->  
  52.     <where>  
  53.       <foreach collection="example.oredCriteria" item="criteria" separator="or">  
  54.         <if test="criteria.valid">  
  55.           <trim prefix="(" prefixOverrides="and" suffix=")">  
  56.             <foreach collection="criteria.criteria" item="criterion">  
  57.               <choose>  
  58.                 <when test="criterion.noValue">  
  59.                   and ${criterion.condition}  
  60.                 </when>  
  61.                 <when test="criterion.singleValue">  
  62.                   and ${criterion.condition} #{criterion.value}  
  63.                 </when>  
  64.                 <when test="criterion.betweenValue">  
  65.                   and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}  
  66.                 </when>  
  67.                 <when test="criterion.listValue">  
  68.                   and ${criterion.condition}  
  69.                   <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">  
  70.                     #{listItem}  
  71.                   </foreach>  
  72.                 </when>  
  73.               </choose>  
  74.             </foreach>  
  75.           </trim>  
  76.         </if>  
  77.       </foreach>  
  78.     </where>  
  79.   </sql>  
  80.   <sql id="Base_Column_List">  
  81.     <!--  
  82.       WARNING - @mbggenerated  
  83.       This element is automatically generated by MyBatis Generator, do not modify.  
  84.     -->  
  85.     USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL  
  86.   </sql>  
  87.   <select id="selectByExample" parameterType="com.lin.domain.UserExample" resultMap="BaseResultMap">  
  88.     <!--  
  89.       WARNING - @mbggenerated  
  90.       This element is automatically generated by MyBatis Generator, do not modify.  
  91.     -->  
  92.     select  
  93.     <if test="distinct">  
  94.       distinct  
  95.     </if>  
  96.     <include refid="Base_Column_List" />  
  97.     from t_user  
  98.     <if test="_parameter != null">  
  99.       <include refid="Example_Where_Clause" />  
  100.     </if>  
  101.     <if test="orderByClause != null">  
  102.       order by ${orderByClause}  
  103.     </if>  
  104.   </select>  
  105.   <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">  
  106.     <!--  
  107.       WARNING - @mbggenerated  
  108.       This element is automatically generated by MyBatis Generator, do not modify.  
  109.     -->  
  110.     select   
  111.     <include refid="Base_Column_List" />  
  112.     from t_user  
  113.     where USER_ID = #{userId,jdbcType=INTEGER}  
  114.   </select>  
  115.   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">  
  116.     <!--  
  117.       WARNING - @mbggenerated  
  118.       This element is automatically generated by MyBatis Generator, do not modify.  
  119.     -->  
  120.     delete from t_user  
  121.     where USER_ID = #{userId,jdbcType=INTEGER}  
  122.   </delete>  
  123.   <delete id="deleteByExample" parameterType="com.lin.domain.UserExample">  
  124.     <!--  
  125.       WARNING - @mbggenerated  
  126.       This element is automatically generated by MyBatis Generator, do not modify.  
  127.     -->  
  128.     delete from t_user  
  129.     <if test="_parameter != null">  
  130.       <include refid="Example_Where_Clause" />  
  131.     </if>  
  132.   </delete>  
  133.   <insert id="insert" parameterType="com.lin.domain.User">  
  134.     <!--  
  135.       WARNING - @mbggenerated  
  136.       This element is automatically generated by MyBatis Generator, do not modify.  
  137.     -->  
  138.     insert into t_user (USER_ID, USER_NAME, USER_PASSWORD,   
  139.       USER_EMAIL)  
  140.     values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=CHAR}, #{userPassword,jdbcType=CHAR},   
  141.       #{userEmail,jdbcType=CHAR})  
  142.   </insert>  
  143.   <insert id="insertSelective" parameterType="com.lin.domain.User">  
  144.     <!--  
  145.       WARNING - @mbggenerated  
  146.       This element is automatically generated by MyBatis Generator, do not modify.  
  147.     -->  
  148.     insert into t_user  
  149.     <trim prefix="(" suffix=")" suffixOverrides=",">  
  150.       <if test="userId != null">  
  151.         USER_ID,  
  152.       </if>  
  153.       <if test="userName != null">  
  154.         USER_NAME,  
  155.       </if>  
  156.       <if test="userPassword != null">  
  157.         USER_PASSWORD,  
  158.       </if>  
  159.       <if test="userEmail != null">  
  160.         USER_EMAIL,  
  161.       </if>  
  162.     </trim>  
  163.     <trim prefix="values (" suffix=")" suffixOverrides=",">  
  164.       <if test="userId != null">  
  165.         #{userId,jdbcType=INTEGER},  
  166.       </if>  
  167.       <if test="userName != null">  
  168.         #{userName,jdbcType=CHAR},  
  169.       </if>  
  170.       <if test="userPassword != null">  
  171.         #{userPassword,jdbcType=CHAR},  
  172.       </if>  
  173.       <if test="userEmail != null">  
  174.         #{userEmail,jdbcType=CHAR},  
  175.       </if>  
  176.     </trim>  
  177.   </insert>  
  178.   <select id="countByExample" parameterType="com.lin.domain.UserExample" resultType="java.lang.Integer">  
  179.     <!--  
  180.       WARNING - @mbggenerated  
  181.       This element is automatically generated by MyBatis Generator, do not modify.  
  182.     -->  
  183.     select count(*) from t_user  
  184.     <if test="_parameter != null">  
  185.       <include refid="Example_Where_Clause" />  
  186.     </if>  
  187.   </select>  
  188.   <update id="updateByExampleSelective" parameterType="map">  
  189.     <!--  
  190.       WARNING - @mbggenerated  
  191.       This element is automatically generated by MyBatis Generator, do not modify.  
  192.     -->  
  193.     update t_user  
  194.     <set>  
  195.       <if test="record.userId != null">  
  196.         USER_ID = #{record.userId,jdbcType=INTEGER},  
  197.       </if>  
  198.       <if test="record.userName != null">  
  199.         USER_NAME = #{record.userName,jdbcType=CHAR},  
  200.       </if>  
  201.       <if test="record.userPassword != null">  
  202.         USER_PASSWORD = #{record.userPassword,jdbcType=CHAR},  
  203.       </if>  
  204.       <if test="record.userEmail != null">  
  205.         USER_EMAIL = #{record.userEmail,jdbcType=CHAR},  
  206.       </if>  
  207.     </set>  
  208.     <if test="_parameter != null">  
  209.       <include refid="Update_By_Example_Where_Clause" />  
  210.     </if>  
  211.   </update>  
  212.   <update id="updateByExample" parameterType="map">  
  213.     <!--  
  214.       WARNING - @mbggenerated  
  215.       This element is automatically generated by MyBatis Generator, do not modify.  
  216.     -->  
  217.     update t_user  
  218.     set USER_ID = #{record.userId,jdbcType=INTEGER},  
  219.       USER_NAME = #{record.userName,jdbcType=CHAR},  
  220.       USER_PASSWORD = #{record.userPassword,jdbcType=CHAR},  
  221.       USER_EMAIL = #{record.userEmail,jdbcType=CHAR}  
  222.     <if test="_parameter != null">  
  223.       <include refid="Update_By_Example_Where_Clause" />  
  224.     </if>  
  225.   </update>  
  226.   <update id="updateByPrimaryKeySelective" parameterType="com.lin.domain.User">  
  227.     <!--  
  228.       WARNING - @mbggenerated  
  229.       This element is automatically generated by MyBatis Generator, do not modify.  
  230.     -->  
  231.     update t_user  
  232.     <set>  
  233.       <if test="userName != null">  
  234.         USER_NAME = #{userName,jdbcType=CHAR},  
  235.       </if>  
  236.       <if test="userPassword != null">  
  237.         USER_PASSWORD = #{userPassword,jdbcType=CHAR},  
  238.       </if>  
  239.       <if test="userEmail != null">  
  240.         USER_EMAIL = #{userEmail,jdbcType=CHAR},  
  241.       </if>  
  242.     </set>  
  243.     where USER_ID = #{userId,jdbcType=INTEGER}  
  244.   </update>  
  245.   <update id="updateByPrimaryKey" parameterType="com.lin.domain.User">  
  246.     <!--  
  247.       WARNING - @mbggenerated  
  248.       This element is automatically generated by MyBatis Generator, do not modify.  
  249.     -->  
  250.     update t_user  
  251.     set USER_NAME = #{userName,jdbcType=CHAR},  
  252.       USER_PASSWORD = #{userPassword,jdbcType=CHAR},  
  253.       USER_EMAIL = #{userEmail,jdbcType=CHAR}  
  254.     where USER_ID = #{userId,jdbcType=INTEGER}  
  255.   </update>  
  256. </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下面

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  4. <configuration>  
  5. </configuration>  
<?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配置

  1. <beans xmlns="http://www.springframework.org/schema/beans"    
  2.     xmlns:context="http://www.springframework.org/schema/context"    
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"    
  4.      xmlns:mvc="http://www.springframework.org/schema/mvc"      
  5.     xsi:schemaLocation="      
  6.         http://www.springframework.org/schema/mvc     
  7.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
  8.         http://www.springframework.org/schema/beans           
  9.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd      
  10.         http://www.springframework.org/schema/mvc        
  11.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
  12.         http://www.springframework.org/schema/context       
  13.         http://www.springframework.org/schema/context/spring-context-3.0.xsd">    
  14.     <!-- 把标记了@Controller注解的类转换为bean -->    
  15.     <context:component-scan base-package="com.lin.controller" />    
  16.     <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->    
  17.     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />    
  18.    <!-- 静态资源访问(不拦截此目录下的东西的访问) -->      
  19.     <mvc:annotation-driven />      
  20.     <mvc:resources location="/WEB-INF//js/"  mapping="/js/**" />   
  21.     <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->    
  22.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"    
  23.         p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>    
  24.   
  25.     
  26. </beans>  
<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下面

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="    
  6.            http://www.springframework.org/schema/beans    
  7.            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  8.            http://www.springframework.org/schema/aop    
  9.            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  10.            http://www.springframework.org/schema/context    
  11.            http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  12.     <!-- 配置数据源 -->  
  13.     <bean id="dataSource"  
  14.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  15.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  16.         <property name="url" value="jdbc:mysql://localhost:3306/learning" />  
  17.         <property name="username" value="root" />  
  18.         <property name="password" value="christmas258@" />  
  19.     </bean>  
  20.   
  21.     <!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 -->  
  22.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  23.         <property name="basePackage"  
  24.             value="com.lin.dao" />  
  25.     </bean>  
  26.   
  27. <!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置-->  
  28.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  29.         <property name="dataSource" ref="dataSource" />  
  30.        <property name="mapperLocations" value="classpath*:com/lin/mapper/**/*.xml"/>    
  31.         <property name="configLocation" value="classpath:mybatis-config.xml" />  
  32.         <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"   
  33.             /> -->  
  34.     </bean>  
  35.   
  36.     <!-- 自动扫描注解的bean -->  
  37.     <context:component-scan base-package="com.lin.controller" />  
  38.         <context:component-scan base-package="com.lin.service.impl" />  
  39.   
  40. </beans>  
<?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="christmas258@" />
	</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下面

  1. log4j.rootLogger =DEBEG,stdout,debug  
  2.     
  3.     
  4. log4j.appender.stdout = org.apache.log4j.ConsoleAppender    
  5. log4j.appender.stdout.Target = System.out    
  6. log4j.appender.stdout.layout = org.apache.log4j.PatternLayout    
  7. log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n    
  8.     
  9. log4j.logger.java.sql.ResultSet=INFO  
  10. log4j.logger.org.apache=INFO  
  11. log4j.logger.java.sql.Connection=DEBUG  
  12. log4j.logger.java.sql.Statement=DEBUG  
  13. log4j.logger.java.sql.PreparedStatement=DEBUG   
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下面

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <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">  
  3.   <display-name>JsLearning3</display-name>  
  4.   <welcome-file-list>  
  5.     <welcome-file>index.html</welcome-file>  
  6.     <welcome-file>index.htm</welcome-file>  
  7.     <welcome-file>index.jsp</welcome-file>  
  8.     <welcome-file>default.html</welcome-file>  
  9.     <welcome-file>default.htm</welcome-file>  
  10.     <welcome-file>default.jsp</welcome-file>  
  11.   </welcome-file-list>  
  12.     
  13.         <!-- Spring 容器加载 -->    
  14.     <listener>    
  15.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    
  16.     </listener>    
  17.     <context-param>    
  18.         <param-name>contextConfigLocation</param-name>    
  19.         <param-value>classpath:application.xml</param-value>    
  20.     </context-param>   
  21.       
  22.     <!-- 统一设置编码,防止出现中文乱码 -->    
  23.     <filter>  
  24.         <filter-name>Set Character Encoding</filter-name>  
  25.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  26.         <init-param>  
  27.             <param-name>encoding</param-name>  
  28.             <param-value>UTF-8</param-value>  
  29.         </init-param>  
  30.     </filter>  
  31.     <filter-mapping>  
  32.         <filter-name>Set Character Encoding</filter-name>  
  33.         <url-pattern>/*</url-pattern>  
  34.     </filter-mapping>  
  35.     
  36.    <!-- SpringMVC的前端控制器 -->    
  37.     <servlet>    
  38.         <servlet-name>dispatcherServlet</servlet-name>    
  39.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
  40.         <!-- 设置自己定义的控制器xml文件 -->    
  41.         <init-param>    
  42.             <param-name>contextConfigLocation</param-name>    
  43.             <param-value>classpath*:spring-servlet.xml</param-value>    
  44.         </init-param>    
  45.         <load-on-startup>1</load-on-startup>    
  46.     </servlet>    
  47.     <!-- Spring MVC配置文件结束 -->    
  48.     
  49.     <!-- 拦截设置 -->    
  50.     <servlet-mapping>    
  51.         <servlet-name>dispatcherServlet</servlet-name>    
  52.         <!-- 由SpringMVC拦截所有请求 -->    
  53.         <url-pattern>/</url-pattern>    
  54.     </servlet-mapping>    
  55.       
  56.     <!-- webAppRootKey:值缺省为webapp.root,当tomcat下部署多个应用时(每个都用到了log4j), 每个应用的web.xml中都要配置该参数,该参数与Log4j.xml文件中的${webapp.root}  
  57.         否则每个应用的webAppRootKey值都相同,就会引起冲突  
  58.      -->  
  59.     <context-param>  
  60.         <param-name>webAppRootKey</param-name>  
  61.         <param-value>webApp.root</param-value>  
  62.     </context-param>  
  63.     <!-- log4jConfigLocation:log4j配置文件存放路径 -->  
  64.     <context-param>  
  65.         <param-name>log4jConfigLocation</param-name>  
  66.         <param-value>classpath:log4j.properties</param-value>  
  67.     </context-param>  
  68.     <!-- 3000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;这样便于日志存放位置的改变 -->    
  69.     <context-param>      
  70.          <param-name>log4jRefreshInterval</param-name>      
  71.          <param-value>3000</param-value>      
  72.     </context-param>     
  73.     <listener>  
  74.         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  75.     </listener>  
  76. </web-app>  
<?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编程

  1. var process_request = "<img src='loading.gif' width='16' height='16' border='0' align='absmiddle'>正在数据处理中...";    
  2. var username_empty = "<span style='COLOR:#ff0000'>  × 用户名不能为空!</span>";    
  3. var username_shorter = "<span style='COLOR:#ff0000'> × 用户名长度不能少于 3 个字符。</span>";    
  4. var username_longer = "<span style='COLOR:#ff0000'> × 用户名长度不能大于 30个字符。</span>";    
  5. var username_invalid = "- 用户名只能是由字母数字以及下划线组成。";    
  6. var username_have_register = "<span style='COLOR:#ff0000'> × 用户名已经存在,请重新输入!</span>";    
  7. var username_can_register="<span style='COLOR:#006600'> √ 恭喜您!该用户名可以注册!</span>";    
  8. var password_empty = "<span style='COLOR:#ff0000'> × 登录密码不能为空。</span>";    
  9. var password_shorter_s = "<span style='COLOR:#ff0000'> × 登录密码不能少于 6 个字符。</span>";    
  10. var password_shorter_m = "<span style='COLOR:#ff0000'> × 登录密码不能多于 30 个字符。</span>";    
  11. var confirm_password_invalid = "<span style='COLOR:#ff0000'> × 两次输入密码不一致!</span>";    
  12. var email_empty = "<span style='COLOR:#ff0000'> × 邮箱不能为空!</span>";    
  13. var email_invalid = "<span style='COLOR:#ff0000'> × 邮箱格式出错!</span>";    
  14. var email_have_register = "<span style='COLOR:#ff0000'> × 该邮箱已被注册! </span>";    
  15. var email_can_register = "<span style='COLOR:#006600'> √ 邮箱可以注册!</span>";    
  16. var agreement_no = "<span style='COLOR:#ff0000'> × 您没有接受协议</span>";    
  17. var agreement_yes= "<span style='COLOR:#006600'> √ 已经接受协议</span>";    
  18. var info_can="<span style='COLOR:#006600'> √ 可以注册!</span>";    
  19. var info_right="<span style='COLOR:#006600'> √ 填写正确!</span>";   
  20. var name_flag=false;  
  21. var email_flag=false;  
  22. var password_flag=false;  
  23. var accept_flag=false;  
  24.   
  25. $(function(){  
  26.     change_submit();      
  27.     if(document.getElementById("agreement").checked){  
  28.         alert("checkbox is checked");  
  29.     }  
  30. });   
  31.   
  32. /* 
  33.  * 获取工程的路径 
  34.  */  
  35. function getRootPath() {  
  36.     var pathName = window.location.pathname.substring(1);  
  37.     var webName = pathName == '' ? '' : pathName.substring(0, pathName  
  38.             .indexOf('/'));  
  39.     return window.location.protocol + '//' + window.location.host + '/'  
  40.             + webName + '/';  
  41. }  
  42. /* 
  43.  * 用户名检测 
  44.  */  
  45. function checkUserName(obj) {  
  46.     if (checks(obj.value) == false) {  
  47.         showInfo("username_notice", username_invalid);  
  48.     } else if (obj.value.length < 1) {  
  49.         showInfo("username_notice", username_empty);  
  50.     }else if (obj.value.length < 3) {  
  51.         showInfo("username_notice", username_shorter);  
  52.     } else if(obj.value.length>30){  
  53.         showInfo("username_notice", username_longer);  
  54.     }else {       
  55.         // 调用Ajax函数,向服务器端发送查询  
  56.         $.ajax({ //一个Ajax过程  
  57.             type: "post"//以post方式与后台沟通  
  58.             url :getRootPath()+"/register/checkUserName"//与此页面沟通  
  59.             dataType:'json',//返回的值以 JSON方式 解释  
  60.             data: 'userName='+obj.value, //发给的数据  
  61.             success: function(json){//如果调用成功  
  62.                 if(json.flag){  
  63.                     showInfo("username_notice", username_have_register);  
  64.                 }else {  
  65.                     showInfo("username_notice", username_can_register);  
  66.                     name_flag=true;  
  67.                     change_submit();  
  68.                     return;  
  69.                 }  
  70.             }     
  71.     });   
  72.     }  
  73.     name_flag=false;  
  74.     change_submit();  
  75. }    
  76. /* 
  77.  * 用户名检测是否包含非法字符 
  78.  */  
  79. function checks(t) {  
  80.     szMsg = "[#%&\'\"\\,;:=!^@]"  
  81.     for (i = 1; i < szMsg.length + 1; i++) {  
  82.         if (t.indexOf(szMsg.substring(i - 1, i)) > -1) {  
  83.             return false;  
  84.         }  
  85.     }  
  86.     return true;  
  87. }  
  88. /* 
  89.  * 邮箱检测 
  90.  */  
  91.  function checkEmail(email) {  
  92.     var re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/  
  93.     if (email.value.length < 1) {  
  94.         showInfo("email_notice", email_empty);  
  95.     } else if (!re.test(email.value)) {  
  96.         email.className = "FrameDivWarn";  
  97.         showInfo("email_notice", email_invalid);          
  98.     } else {  
  99.         // 调用Ajax函数,向服务器端发送查询  
  100.        $.ajax({ //一个Ajax过程  
  101.             type: "post"//以post方式与后台沟通  
  102.             url :getRootPath()+"/register/checkEmail"//与此页面沟通  
  103.             dataType:'json',//返回的值以 JSON方式 解释  
  104.             data: 'email='+email.value, //发给的数据  
  105.             success: function(json){//如果调用成功  
  106.                 if(json.flag){  
  107.                     showInfo("email_notice", email_have_register);  
  108.                 }else {  
  109.                     showInfo("email_notice", email_can_register);  
  110.                     email_flag=true;  
  111.                     change_submit();  
  112.                     return;  
  113.                 }  
  114.             }     
  115.       });  
  116.     }  
  117.     email_flag=false;  
  118.     change_submit();  
  119. }   
  120.    
  121.   
  122.   
  123. /* 
  124.  * 密码检测 
  125.  */  
  126.  function checkPassword( password )    
  127.  {    
  128.      if(password.value.length < 1){  
  129.          password_flag=false;  
  130.          showInfo("password_notice",password_empty);    
  131.      }else if ( password.value.length < 6 )    
  132.      {    
  133.          password_flag=false;  
  134.          showInfo("password_notice",password_shorter_s);    
  135.      }    
  136.      else if(password.value.length > 30){    
  137.          password_flag=false;  
  138.          showInfo("password_notice",password_shorter_m);    
  139.          }    
  140.      else    
  141.      {    
  142.          showInfo("password_notice",info_right);    
  143.      }    
  144.      change_submit();  
  145.  }    
  146.    
  147.  /* 
  148.   * 密码确认检测 
  149.   */  
  150.  function checkConformPassword(conform_password)    
  151.  {    
  152.      password = $("#password").val();    
  153.      if (password.length < 1)  {        
  154.          showInfo("conform_password_notice",password_empty);    
  155.            
  156.      } else if ( conform_password.value!= password)    
  157.      {    
  158.          showInfo("conform_password_notice",confirm_password_invalid);    
  159.      }    
  160.      else    
  161.      {       
  162.          showInfo("conform_password_notice",info_right);    
  163.             password_flag=true;  
  164.             change_submit();  
  165.             return;  
  166.      }    
  167.      password_flag=false;  
  168.     change_submit();  
  169.   
  170.  }  
  171.    
  172.  /* 
  173.   * 检测密码强度检测 
  174.   */  
  175.  function checkIntensity(pwd)    
  176.  {    
  177.    var Mcolor = "#FFF",Lcolor = "#FFF",Hcolor = "#FFF";    
  178.    var m=0;    
  179.      
  180.    var Modes = 0;    
  181.    for (i=0; i<pwd.length; i++)    
  182.    {    
  183.      var charType = 0;    
  184.      var t = pwd.charCodeAt(i);    
  185.      if (t>=48 && t <=57)    
  186.      {    
  187.        charType = 1;    
  188.      }    
  189.      else if (t>=65 && t <=90)    
  190.      {    
  191.        charType = 2;    
  192.      }    
  193.      else if (t>=97 && t <=122)    
  194.        charType = 4;    
  195.      else    
  196.        charType = 4;    
  197.      Modes |= charType;    
  198.    }    
  199.      
  200.    for (i=0;i<4;i++)    
  201.    {    
  202.      if (Modes & 1) m++;    
  203.        Modes>>>=1;    
  204.    }    
  205.      
  206.    if (pwd.length<=4)    
  207.    {    
  208.      m = 1;    
  209.    }    
  210.      
  211.    switch(m)    
  212.    {    
  213.      case 1 :    
  214.        Lcolor = "2px solid red";    
  215.        Mcolor = Hcolor = "2px solid #DADADA";    
  216.      break;    
  217.      case 2 :    
  218.        Mcolor = "2px solid #f90";    
  219.        Lcolor = Hcolor = "2px solid #DADADA";    
  220.      break;    
  221.      case 3 :    
  222.        Hcolor = "2px solid #3c0";    
  223.        Lcolor = Mcolor = "2px solid #DADADA";    
  224.      break;    
  225.      case 4 :    
  226.        Hcolor = "2px solid #3c0";    
  227.        Lcolor = Mcolor = "2px solid #DADADA";    
  228.      break;    
  229.      default :    
  230.        Hcolor = Mcolor = Lcolor = "";    
  231.      break;    
  232.    }    
  233.    document.getElementById("pwd_lower").style.borderBottom  = Lcolor;    
  234.    document.getElementById("pwd_middle").style.borderBottom = Mcolor;    
  235.    document.getElementById("pwd_high").style.borderBottom   = Hcolor;      
  236.  }  
  237.    
  238. //--------------注册协议复选框状态检测---------------------//    
  239.  function checkAgreement(obj){         
  240.     if(document.getElementById("agreement").checked){  
  241.          showInfo("agreement_notice",agreement_yes);    
  242.         accept_flag=true;  
  243.         change_submit();  
  244.         }else{  
  245.         showInfo("agreement_notice",agreement_no);    
  246.               
  247.         }  
  248. /*   if($("#agreement").attr("checked")=="checked"){ 
  249.          alert('选中'); 
  250.      }*/  
  251. /*   if (document.formUser.agreement.checked==false)   
  252.    {   
  253.       showInfo("agreement_notice",checkAgreement);   
  254.  } else {   
  255.      showInfo("agreement_notice",info_right);   
  256.      } */   
  257.  }  
  258.  /* 
  259.   * 按钮状态设置 
  260.   */   
  261. function change_submit()    
  262. {         
  263.     if(name_flag&&email_flag&&password_flag&&accept_flag){  
  264.           document.forms['formUser'].elements['Submit1'].disabled = '';    
  265.     }  
  266.    else    
  267.      {    
  268.           document.forms['formUser'].elements['Submit1'].disabled = 'disabled';    
  269.      }    
  270. }    
  271. /* 
  272.  * 公用程序 
  273.  */    
  274.     function showInfo(target,Infos){    
  275.     document.getElementById(target).innerHTML = Infos;    
  276.     }    
  277.     function showclass(target,Infos){    
  278.     document.getElementById(target).className = Infos;    
  279.     }       
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-*\.*)+@(\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、注册页面

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.11.3.min.js" ></script>  
  8. <script type="text/javascript" src="<%=request.getContextPath()%>/js/registerCheck.js" ></script>  
  9. <title>Ajax+SpringMVC+Spring+MyBatis+Mysql注册验证实例</title>  
  10. </head>  
  11. <body>    
  12. <div id="reg">    
  13. <FORM name="formUser"  action="<%=request.getContextPath()%>/register/successed"  method=post>    
  14.   <BR>    
  15.   <TABLE width="100%" align=center border=0>    
  16.     <TBODY>    
  17.       <TR>    
  18.         <TD align=right width="15%"><STRONG>用户名:</STRONG></TD>    
  19.         <TD width="57%"><INPUT id="username" onBlur="checkUserName(this)"     
  20.       name="username">    
  21.             <SPAN id="username_notice" >*</SPAN></TD>    
  22.       </TR>    
  23.       <TR>    
  24.         <TD align=right><STRONG>邮箱:</STRONG></TD>    
  25.         <TD><INPUT id="email" onBlur="checkEmail(this)" name="email">    
  26.             <SPAN id=email_notice >*</SPAN></TD>    
  27.       </TR>    
  28.       <TR>    
  29.         <TD align=right><STRONG>密码:</STRONG></TD>    
  30.         <TD><INPUT id="password" onBlur="checkPassword(this)"     
  31.       onkeyup="checkIntensity(this.value)" type="password" name="password">    
  32.             <SPAN     
  33.       id=password_notice >*</SPAN></TD>    
  34.       </TR>    
  35.       <TR>    
  36.         <TD align=right><STRONG>密码强度:</STRONG></TD>    
  37.         <TD><TABLE cellSpacing=0 cellPadding=1 width=145 border=0>    
  38.           <TBODY>    
  39.             <TR align=middle>    
  40.               <TD id=pwd_lower width="33%"></TD>    
  41.               <TD id=pwd_middle width="33%"></TD>    
  42.               <TD id=pwd_high width="33%"></TD>    
  43.             </TR>    
  44.           </TBODY>    
  45.         </TABLE></TD>    
  46.       </TR>    
  47.       <TR>    
  48.         <TD align=right><STRONG>确认密码:</STRONG></TD>    
  49.         <TD><INPUT id="conform_password" onBlur="checkConformPassword(this)"     
  50.       type="password" name="confirm_password">    
  51.             <SPAN id=conform_password_notice >*</SPAN></TD>    
  52.       </TR>    
  53.       <TR>    
  54.         <TD> </TD>    
  55.         <TD><LABEL>    
  56.           <INPUT type="checkbox" id="agreement" onclick="checkAgreement(this)">    
  57.           <B>我已看过并接受《<a href="#">用户协议</a><SPAN id=agreement_notice >*</SPAN></B></LABEL></TD>    
  58.       </TR>    
  59.       <TR>    
  60.         <TD  ><INPUT type=hidden value=act_register name=act></TD>    
  61.         <TD  ><input type=submit value=确认注册    name="Submit1" class="anniu" disabled></TD>    
  62.       </TR>    
  63.       <TR>    
  64.         <TD colSpan=2> </TD>    
  65.       </TR>    
  66.     </TBODY>    
  67.   </TABLE>    
  68. </FORM>    
  69. </div>             
  70. </body>  
  71. </html>  
<%@ 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)"   
      οnkeyup="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" οnclick="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、注册成功页面

  1. <%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>   
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  3. <html>  
  4. <head>  
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  6. <title>用户注册成功</title>  
  7. </head>  
  8. <body>  
  9. <center>  
  10. <h1><b>欢迎新用户</b></h1>  
  11. 用户名:${requestScope.username}<br>    
  12. 邮箱:${requestScope.email}<br>    
  13. </center>  
  14. </body>  
  15. </html>  
<%@ 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

  1. package com.lin.controller;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.   
  7. import javax.annotation.Resource;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import net.sf.json.JSONObject;  
  12.   
  13. import org.apache.log4j.Logger;  
  14. import org.springframework.stereotype.Controller;  
  15. import org.springframework.web.bind.annotation.RequestMapping;  
  16. import org.springframework.web.bind.annotation.RequestMethod;  
  17. import org.springframework.web.servlet.ModelAndView;  
  18.   
  19. import com.lin.domain.User;  
  20. import com.lin.domain.UserExample;  
  21. import com.lin.domain.UserExample.Criteria;  
  22. import com.lin.service.IRegisterService;  
  23.   
  24. @Controller  
  25. public class RegisterController {  
  26.     private static Logger logger = Logger.getLogger(RegisterController.class);      
  27.     @Resource  
  28.     private IRegisterService registerService;     
  29.       
  30.     @RequestMapping({"/register","/"})  
  31.     public String register(){    
  32.         return "register";  
  33.     }  
  34.     @RequestMapping(value="/register/checkUserName",method = RequestMethod.POST)  
  35.     public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws IOException{  
  36.         String userName=(String)request.getParameter("userName");             
  37.         //检验用户名是否存在  
  38.         UserExample userExample=new UserExample();  
  39.         Criteria conditionCri = userExample.createCriteria();  
  40.         conditionCri.andUserNameEqualTo(userName);        
  41.         int num=registerService.countByExample(userExample);  
  42.         //用户名是否存在的标志  
  43.         boolean flag=false;  
  44.         if(num>0){  
  45.             flag=true;  
  46.         }         
  47.         //将数据转换成json  
  48.         Map<String,Object> map = new HashMap<String,Object>();    
  49.         map.put("flag", flag);              
  50.         String json = JSONObject.fromObject(map).toString();          
  51.         //将数据返回  
  52.         response.setCharacterEncoding("UTF-8");  
  53.         response.flushBuffer();  
  54.         response.getWriter().write(json);  
  55.         response.getWriter().flush();    
  56.         response.getWriter().close();  
  57.         return null;  
  58.     }  
  59.       
  60.     @RequestMapping(value="/register/checkEmail",method = RequestMethod.POST)  
  61.     public String checkEmail(HttpServletRequest request, HttpServletResponse response) throws IOException{  
  62.         String email=(String)request.getParameter("email");           
  63.         //检验邮箱是否存在  
  64.         UserExample userExample=new UserExample();  
  65.         Criteria conditionCri = userExample.createCriteria();  
  66.         conditionCri.andUserEmailEqualTo(email);          
  67.         int num=registerService.countByExample(userExample);  
  68.         //用户名是否存在的标志  
  69.         boolean flag=false;  
  70.         if(num>0){  
  71.             flag=true;  
  72.         }         
  73.         //将数据转换成json  
  74.         Map<String,Object> map = new HashMap<String,Object>();    
  75.         map.put("flag", flag);              
  76.         String json = JSONObject.fromObject(map).toString();          
  77.         //将数据返回  
  78.         response.setCharacterEncoding("UTF-8");  
  79.         response.flushBuffer();  
  80.         response.getWriter().write(json);  
  81.         response.getWriter().flush();    
  82.         response.getWriter().close();  
  83.         return null;  
  84.     }  
  85.     @RequestMapping(value="/register/successed")  
  86.     public ModelAndView  successed(HttpServletRequest request, HttpServletResponse response) throws IOException{  
  87.         String username=(String)request.getParameter("username");     
  88.         String email=(String)request.getParameter("email");       
  89.         String password=(String)request.getParameter("password");  
  90.         if(username==null||email==null||password==null){  
  91.             return new ModelAndView("redirect:/register");   
  92.         }  
  93.         //新增用户插入数据库  
  94.         User user=new User();  
  95.         user.setUserName(username);  
  96.         user.setUserEmail(email);  
  97.         user.setUserPassword(password);  
  98.         registerService.insert(user);         
  99.         //将数据转换成  
  100.         Map<String,Object> map = new HashMap<String,Object>();    
  101.         map.put("username", username);    
  102.         map.put("email", email);    
  103.         map.put("password", password);    
  104. /*      String json = JSONObject.fromObject(map).toString();         
  105.         //将数据返回 
  106.         response.setCharacterEncoding("UTF-8"); 
  107.         response.flushBuffer(); 
  108.         response.getWriter().write(json); 
  109.         response.getWriter().flush();   
  110.         response.getWriter().close();*/  
  111.         return new ModelAndView("successed",map);    
  112.     }  
  113.       
  114.   
  115. }  
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、最后还要看看数据库数据进去了没有:

这是还没注册之前的:

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

本文工程免费下载

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值