SSM基本整合

工程結(jié)構(gòu)如圖所示:


1.Spring系列配置文件

spring-core.xml

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        
    <context:component-scan base-package="com.hsun">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <import resource="classpath:spring/spring-mybatis.xml" />
    
    <!-- 事務(wù)管理 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="poolDataSource" />
    </bean>
    <tx:annotation-driven transaction-manager="txManager" />

</beans>


spring-mvc.xml

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven/>

    <context:component-scan base-package="com.hsun.controller" />
    <!-- 靜態(tài)資源 -->
    <mvc:resources location="/static/" mapping="/static/**"></mvc:resources>
    <!-- 跨域 -->
    <mvc:cors>
        <mvc:mapping path="/**" allowed-origins="*" allow-credentials="true" max-age="1800" allowed-methods="GET"/>
    </mvc:cors>
    <!-- jsp視圖解析器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.InternalResourceView" />
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
</beans>

spring-mybstis

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 1:加載jdbc.properties配置文件 -->
    <context:property-placeholder location="classpath:dbconfig.properties" />

    <!-- 2:配置數(shù)據(jù)庫(kù)連接池 -->
    <bean id="poolDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!-- 配置和mybatis整合 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis全局配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 掃描entity包,使用別名,多個(gè)包;隔開(kāi) -->
        <property name="typeAliasesPackage" value="com.hsun.bean" />
        <property name="dataSource" ref="poolDataSource" />
        <!-- 指定mybatis,mapper配置文件的位置 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    
    <!-- 配置掃描器,將mybatis接口的實(shí)現(xiàn)加入到IOC容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- 掃描所有dao接口的實(shí)現(xiàn),加入到IOC容器中 -->
        <property name="basePackage" value="com.hsun.dao" />
    </bean>

</beans>


2.mybatis系列配置文件

mybstis-config.xml

<?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>
  
  <settings>
    <setting name="mapUnderscoreToCamelCase" value="true"/>
  </settings>
  <typeAliases>
    <package name="com.hsun.bean"/>
  </typeAliases>
  
  
  <!-- <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers> -->
  
  <!-- 注冊(cè)分頁(yè)插件 -->
  <plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- 配置參數(shù)合理化 -->
        <property name="reasonable" value="true"/>
    </plugin>
  </plugins>
  
  
</configuration>

EmployeeMapper.xml

<?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.hsun.dao.EmployeeMapper">
    <resultMap id="BaseResultMap" type="com.hsun.bean.Employee">
        <id column="emp_id" jdbcType="INTEGER" property="empId" />
        <result column="emp_name" jdbcType="VARCHAR" property="empName" />
        <result column="gender" jdbcType="CHAR" property="gender" />
        <result column="email" jdbcType="VARCHAR" property="email" />
        <result column="d_id" jdbcType="INTEGER" property="dId" />
    </resultMap>
    <!-- 指定聯(lián)合查詢(xún)出部門(mén)字段 -->
    <resultMap id="WithDeptResultMap" type="com.hsun.bean.Employee">
        <id column="emp_id" jdbcType="INTEGER" property="empId" />
        <result column="emp_name" jdbcType="VARCHAR" property="empName" />
        <result column="gender" jdbcType="CHAR" property="gender" />
        <result column="email" jdbcType="VARCHAR" property="email" />
        <result column="d_id" jdbcType="INTEGER" property="dId" />
        <association property="department" javaType="com.hsun.bean.Department">
            <id column="dept_id" property="deptId"/>
            <result column="dept_name" property="deptName"/>
        </association>
    </resultMap>
    <sql id="Example_Where_Clause">
        <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">
        <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">
        emp_id, emp_name, gender, email, d_id
    </sql>
    <sql id="WithDept_Column_List">
        e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name
    </sql>
    <!-- 
         List<Employee> selectByExampleWithDept(EmployeeExample example); 
         Employee selectByPrimaryKeyWithDept(Integer empId);
    -->
    <!-- 查詢(xún)員工同時(shí)帶上部門(mén)的 -->
    <select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
        select
        <if test="distinct">
            distinct
        </if>
        <include refid="WithDept_Column_List" />
        FROM tbl_emp e
        LEFT JOIN tbl_dept d ON e.`d_id`=d.`dept_id`
        <if test="_parameter != null">
            <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null">
            order by ${orderByClause}
        </if>
    </select>
    <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
            select
            <include refid="WithDept_Column_List" />
            FROM tbl_emp e
            LEFT JOIN tbl_dept d ON e.`d_id`=d.`dept_id`
            where emp_id = #{empId,jdbcType=INTEGER}
    </select>
    
    <!-- 查詢(xún)員工不帶上帶上部門(mén)的 -->
    <select id="selectByExample" parameterType="com.hsun.bean.EmployeeExample"
        resultMap="BaseResultMap">
        select
        <if test="distinct">
            distinct
        </if>
        <include refid="Base_Column_List" />
        from tbl_emp
        <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">
        select
        <include refid="Base_Column_List" />
        from tbl_emp
        where emp_id = #{empId,jdbcType=INTEGER}
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from tbl_emp
        where emp_id = #{empId,jdbcType=INTEGER}
    </delete>
    <delete id="deleteByExample" parameterType="com.hsun.bean.EmployeeExample">
        delete from tbl_emp
        <if test="_parameter != null">
            <include refid="Example_Where_Clause" />
        </if>
    </delete>
    <insert id="insert" parameterType="com.hsun.bean.Employee">
        insert into tbl_emp (emp_id, emp_name, gender,
        email, d_id)
        values (#{empId,jdbcType=INTEGER}, #{empName,jdbcType=VARCHAR},
        #{gender,jdbcType=CHAR},
        #{email,jdbcType=VARCHAR}, #{dId,jdbcType=INTEGER})
    </insert>
    <insert id="insertSelective" parameterType="com.hsun.bean.Employee">
        insert into tbl_emp
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="empId != null">
                emp_id,
            </if>
            <if test="empName != null">
                emp_name,
            </if>
            <if test="gender != null">
                gender,
            </if>
            <if test="email != null">
                email,
            </if>
            <if test="dId != null">
                d_id,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="empId != null">
                #{empId,jdbcType=INTEGER},
            </if>
            <if test="empName != null">
                #{empName,jdbcType=VARCHAR},
            </if>
            <if test="gender != null">
                #{gender,jdbcType=CHAR},
            </if>
            <if test="email != null">
                #{email,jdbcType=VARCHAR},
            </if>
            <if test="dId != null">
                #{dId,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    <select id="countByExample" parameterType="com.hsun.bean.EmployeeExample"
        resultType="java.lang.Long">
        select count(*) from tbl_emp
        <if test="_parameter != null">
            <include refid="Example_Where_Clause" />
        </if>
    </select>
    <update id="updateByExampleSelective" parameterType="map">
        update tbl_emp
        <set>
            <if test="record.empId != null">
                emp_id = #{record.empId,jdbcType=INTEGER},
            </if>
            <if test="record.empName != null">
                emp_name = #{record.empName,jdbcType=VARCHAR},
            </if>
            <if test="record.gender != null">
                gender = #{record.gender,jdbcType=CHAR},
            </if>
            <if test="record.email != null">
                email = #{record.email,jdbcType=VARCHAR},
            </if>
            <if test="record.dId != null">
                d_id = #{record.dId,jdbcType=INTEGER},
            </if>
        </set>
        <if test="_parameter != null">
            <include refid="Update_By_Example_Where_Clause" />
        </if>
    </update>
    <update id="updateByExample" parameterType="map">
        update tbl_emp
        set emp_id = #{record.empId,jdbcType=INTEGER},
        emp_name = #{record.empName,jdbcType=VARCHAR},
        gender = #{record.gender,jdbcType=CHAR},
        email = #{record.email,jdbcType=VARCHAR},
        d_id = #{record.dId,jdbcType=INTEGER}
        <if test="_parameter != null">
            <include refid="Update_By_Example_Where_Clause" />
        </if>
    </update>
    <update id="updateByPrimaryKeySelective" parameterType="com.hsun.bean.Employee">
        update tbl_emp
        <set>
            <if test="empName != null">
                emp_name = #{empName,jdbcType=VARCHAR},
            </if>
            <if test="gender != null">
                gender = #{gender,jdbcType=CHAR},
            </if>
            <if test="email != null">
                email = #{email,jdbcType=VARCHAR},
            </if>
            <if test="dId != null">
                d_id = #{dId,jdbcType=INTEGER},
            </if>
        </set>
        where emp_id = #{empId,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.hsun.bean.Employee">
        update tbl_emp
        set emp_name = #{empName,jdbcType=VARCHAR},
        gender = #{gender,jdbcType=CHAR},
        email = #{email,jdbcType=VARCHAR},
        d_id = #{dId,jdbcType=INTEGER}
        where emp_id = #{empId,jdbcType=INTEGER}
    </update>
</mapper>

DepartmentMapper.xml

<?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.hsun.dao.DepartmentMapper">
  <resultMap id="BaseResultMap" type="com.hsun.bean.Department">
    <id column="dept_id" jdbcType="INTEGER" property="deptId" />
    <result column="dept_name" jdbcType="VARCHAR" property="deptName" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <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">
    <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">
    dept_id, dept_name
  </sql>
  <select id="selectByExample" parameterType="com.hsun.bean.DepartmentExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from tbl_dept
    <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">
    select 
    <include refid="Base_Column_List" />
    from tbl_dept
    where dept_id = #{deptId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from tbl_dept
    where dept_id = #{deptId,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.hsun.bean.DepartmentExample">
    delete from tbl_dept
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.hsun.bean.Department">
    insert into tbl_dept (dept_id, dept_name)
    values (#{deptId,jdbcType=INTEGER}, #{deptName,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.hsun.bean.Department">
    insert into tbl_dept
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="deptId != null">
        dept_id,
      </if>
      <if test="deptName != null">
        dept_name,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="deptId != null">
        #{deptId,jdbcType=INTEGER},
      </if>
      <if test="deptName != null">
        #{deptName,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.hsun.bean.DepartmentExample" resultType="java.lang.Long">
    select count(*) from tbl_dept
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update tbl_dept
    <set>
      <if test="record.deptId != null">
        dept_id = #{record.deptId,jdbcType=INTEGER},
      </if>
      <if test="record.deptName != null">
        dept_name = #{record.deptName,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update tbl_dept
    set dept_id = #{record.deptId,jdbcType=INTEGER},
      dept_name = #{record.deptName,jdbcType=VARCHAR}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.hsun.bean.Department">
    update tbl_dept
    <set>
      <if test="deptName != null">
        dept_name = #{deptName,jdbcType=VARCHAR},
      </if>
    </set>
    where dept_id = #{deptId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.hsun.bean.Department">
    update tbl_dept
    set dept_name = #{deptName,jdbcType=VARCHAR}
    where dept_id = #{deptId,jdbcType=INTEGER}
  </update>
</mapper>

3.數(shù)據(jù)源信息

db.properties

jdbc.url=jdbc:mysql://localhost:3306/ssm_crud
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root


4.日志

log4j.rootLogger=INFO,Console,File  
#\u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#\u53EF\u4EE5\u7075\u6D3B\u5730\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  

#\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55
log4j.appender.File.File = logs/ssm.log  
#\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F
log4j.appender.File.MaxFileSize = 10MB  
# \u8F93\u51FA\u6240\u4EE5\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n  


5. web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
 
 <welcome-file-list>
     <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <!-- spring核心的位置 -->
 <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:spring/spring-core.xml</param-value>
 </context-param>
 <!-- 統(tǒng)一編碼filter -->
 <filter>
     <filter-name>charsetEncoding</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>
     <init-param>
         <param-name>forceEncoding</param-name>
         <param-value>true</param-value>
     </init-param>
 </filter>
 

 <!-- 此監(jiān)聽(tīng)器出用于主要為了解決java.beans.Introspector導(dǎo)致內(nèi)存泄漏的問(wèn)題. This listener should 
     be registered as the first one in web.xml, before any application listeners 
     such as Spring's ContextLoaderListener. -->
 <listener>
     <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
 </listener>
 <!-- 加載spring核心的listener -->
 <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <!-- springmvc前端控制器配置 -->
 <servlet>
     <servlet-name>mvc</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:/spring/spring-mvc.xml</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
     <servlet-name>mvc</servlet-name>
     <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>


6. 通用返回類(lèi)

package com.hsun.bean;

import java.util.HashMap;
import java.util.Map;



/**
 * 通用的返回類(lèi)
 * @author 孫浩
 *
 */
public class Msg {
    //狀態(tài)碼100-成功 200-失敗
    private int code;
    //提示信息
    private String msg;
    //要返回給瀏覽器的數(shù)據(jù)
    private Map<String, Object> extend = new HashMap<>();
    
    public static Msg success() {
        Msg result = new Msg();
        result.setCode(100);
        result.setMsg("處理成功");
        return result;
    }
    
    public static Msg fail() {
        Msg result = new Msg();
        result.setCode(200);
        result.setMsg("處理失敗");
        return result;
    }
    
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Map<String, Object> getExtend() {
        return extend;
    }
    public void setExtend(Map<String, Object> extend) {
        this.extend = extend;
    }

    public Msg add(String key, Object value) {
        this.getExtend().put(key, value);
        return this;
    }
    
}


7.首頁(yè)展示

index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<%
    pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<!-- web的路徑問(wèn)題:
不以“/”開(kāi)頭的相對(duì)路徑,找資源以當(dāng)前路徑為基準(zhǔn),經(jīng)常容易出問(wèn)題
以“/”開(kāi)始的路徑在找資源時(shí),是以服務(wù)器的路徑為標(biāo)準(zhǔn),需要加上項(xiàng)目名
 -->
<!-- 引入Jquery -->
<script type="text/javascript"
    src="${APP_PATH }/static/js/jquery.min.js"></script>
<!-- Bootstrap -->
<link
    href="${APP_PATH }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
    rel="stylesheet">
<!-- 引入BootStrap js文件 -->
<script
    src="${APP_PATH }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

<style type="text/css">
#dep_search {
    margin: 0px;
    border: 0px;
}
</style>
</head>
<body>
    <!-- 搭建顯示頁(yè)面 -->

    <!-- 員工添加模態(tài)框 -->
    <div class="modal fade" id="empAddModal" tabindex="-1" role="dialog"
        aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel">員工添加</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">empName</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" name="empName"
                                    id="emp_add_input" placeholder="empName"> <span
                                    class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">email</label>
                            <div class="col-sm-10">
                                <input type="text" name="email" class="form-control"
                                    id="email_add_input" placeholder="email@qq.com"> <span
                                    class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">gender</label>
                            <div class="col-sm-10">
                                <label class="radio-inline"> <input type="radio"
                                    name="gender" id="inlineRadio1" value="M" checked> 男
                                </label> <label class="radio-inline"> <input type="radio"
                                    name="gender" id="inlineRadio2" value="F"> 女
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">gender</label>
                            <div class="col-sm-4">
                                <select class="form-control" name="dId" id="dept_add_select">
                                </select>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default"
                                data-dismiss="modal">關(guān)閉</button>
                            <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <!-- 員工添加模態(tài)框結(jié)束 -->


    <!-- 員工修改模態(tài)框 -->
    <div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog"
        aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title">員工修改</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" id="empUpdateModal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">empName</label>
                            <div class="col-sm-10">
                                <p class="form-control-static" id="empName_update_static"></p>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">email</label>
                            <div class="col-sm-10">
                                <input type="text" name="email" class="form-control"
                                    id="email_update_input" placeholder="email@qq.com"> <span
                                    class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">gender</label>
                            <div class="col-sm-10">
                                <label class="radio-inline"> <input type="radio"
                                    name="gender" id="gender1_update_input" value="M" checked>
                                    男
                                </label> <label class="radio-inline"> <input type="radio"
                                    name="gender" id="gender2_update_input" value="F"> 女
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">gender</label>
                            <div class="col-sm-4">
                                <select class="form-control" name="dId">
                                </select>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default"
                                data-dismiss="modal">關(guān)閉</button>
                            <button type="button" class="btn btn-primary" id="emp_update_btn">更新</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <!-- 員工修改模態(tài)框結(jié)束 -->


    <div class="container">
        <!-- 標(biāo)題 -->
        <div class="row">
            <div class="col-md-12">
                <h1>SSM_CRUD</h1>
            </div>
        </div>

        <div class="row">
            <div class="col-md-8 col-md-offset-4">
                <input aria-describedby="basic-addon1" type="text" id="input_search"
                    placeholder="在此輸入要檢索的內(nèi)容。。。">
                <button class="btn btn-primary btn-default" id="dep_search">
                    <span class="glyphicon glyphicon-search"></span>
                </button>
            </div>
        </div>
        <!-- 按鈕 -->
        <div class="row">
            <div class="col-md-4 col-md-offset-8">
                <button class="btn btn-primary btn-sm" id="emp_add_modal_btn">新增</button>
                <button class="btn btn-danger btn-sm" id="emp_delete_all_btn">刪除</button>
            </div>
        </div>
        <!-- 顯示表格數(shù)據(jù) -->
        <div class="row">
            <div class="col-md-12">
                <table class="table table-hover" id="emps_table">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="check_all"></th>
                            <th>#</th>
                            <th>empName</th>
                            <th>gender</th>
                            <th>email</th>
                            <th>deptName</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
        <!-- 顯示分頁(yè)信息 -->
        <div class="row">
            <!-- 分頁(yè)文字信息 -->
            <div class="col-md-6" id="page_info_area"></div>
            <!-- 分頁(yè)條信息 -->
            <div class="col-md-6" id="page_nav_area"></div>
        </div>
    </div>
    <script type="text/javascript">
        var totalRecord, currentPage; //總記錄數(shù)和當(dāng)前頁(yè)碼

        $(function() {
            to_page(1);

        });

        function to_page(pn) {
            $.ajax({
                type : "GET",
                url : "${APP_PATH }/emps",
                data : "pn=" + pn,
                success : function(result) {
                    //alert(msg.code);
                    //console.log(result);
                    //1.解析并顯示員工數(shù)據(jù)
                    build_emps_table(result);
                    //2.解析并顯示分頁(yè)信息
                    build_page_info(result);
                    //3.解析并顯示分頁(yè)條
                    build_page_nav(result);
                }
            });
        }

        function build_emps_table(result) {
            //每次添加數(shù)據(jù)之前清空表格
            $("#emps_table tbody").empty();
            var emps = result.extend.pageInfo.list;//取到所有查詢(xún)到的封裝到list中的員工
            $
                    .each(
                            emps,
                            function(index, item) {
                                //alert(item.empName);
                                var checkBoxTd = $("<td><input type='checkbox' class='check_item'></td>");
                                var empIdTd = $("<td></td>").append(item.empId);
                                var empNameTd = $("<td></td>").append(
                                        item.empName);
                                var genderTd = $("<td></td>").append(
                                        item.gender == 'M' ? "男" : "女");
                                var emailTd = $("<td></td>").append(item.email);
                                var deptNameTd = $("<td></td>").append(
                                        item.department.deptName);
                                var editBt = $("<button></button>").addClass(
                                        "btn btn-primary btn-sm edit_btn")
                                        .append("<span></span>").addClass(
                                                "glyphicon glyphicon-pencil")
                                        .append("編輯");
                                //為編輯按鈕添加一個(gè)自定義屬性
                                editBt.attr("edit-id", item.empId);
                                var delBt = $("<button></button>").addClass(
                                        "btn btn-danger btn-sm delete_btn")
                                        .append("<span></span>").addClass(
                                                "glyphicon glyphicon-trash")
                                        .append("刪除");
                                //為刪除按鈕添加一個(gè)自定義屬性來(lái)表示當(dāng)前要?jiǎng)h除員工的id
                                delBt.attr("del-id", item.empId);
                                var btnTd = $("<td></td>").append(editBt)
                                        .append(" ").append(delBt);
                                //append()方法每次執(zhí)行完成之后還是返回原來(lái)的元素
                                $("<tr></tr>").append(checkBoxTd).append(
                                        empIdTd).append(empNameTd).append(
                                        genderTd).append(emailTd).append(
                                        deptNameTd).append(btnTd).appendTo(
                                        "#emps_table tbody");
                            });
        }

        //構(gòu)構(gòu)建分頁(yè)信息
        function build_page_info(result) {
            $("#page_info_area").empty();
            $("#page_info_area").append(
                    "當(dāng)前第" + result.extend.pageInfo.pageNum + "頁(yè),共"
                            + result.extend.pageInfo.pages + "頁(yè),共有"
                            + result.extend.pageInfo.total + "條記錄");
            totalRecord = result.extend.pageInfo.total;
            currentPage = result.extend.pageInfo.pageNum;
        }
        //構(gòu)建分頁(yè)條,點(diǎn)擊分頁(yè)條要能去下一頁(yè)等等           
        function build_page_nav(result) {
            //構(gòu)建分頁(yè)導(dǎo)航之前將頁(yè)面清空
            $("#page_nav_area").empty();
            var ul = $("<ul></ul>").addClass("pagination");
            var firstPageLi = $("<li></li>").append(
                    $("<a></a>").append("首頁(yè)").attr("href", "#"));
            var prePageLi = $("<li></li>").append(
                    $("<a></a>").append("&laquo;"));
            //如果沒(méi)有上一頁(yè)則給上一頁(yè)和首頁(yè)添加不可點(diǎn)擊的效果
            if (result.extend.pageInfo.hasPreviousPage == false) {
                firstPageLi.addClass("disabled");
                prePageLi.addClass("disabled");
            } else {
                //為素添加點(diǎn)擊翻頁(yè)事件
                firstPageLi.click(function() {
                    to_page(1);
                });
                prePageLi.click(function() {
                    to_page(result.extend.pageInfo.pageNum - 1);
                });
            }

            var nextPageLi = $("<li></li>").append(
                    $("<a></a>").append("&raquo;"));
            var lastPageLi = $("<li></li>").append(
                    $("<a></a>").append("末頁(yè)").attr("href", "#"));
            //如果沒(méi)有下一頁(yè)則給下一頁(yè)和末頁(yè)添加不可點(diǎn)擊的效果
            if (result.extend.pageInfo.hasNextPage == false) {
                nextPageLi.addClass("disabled");
                lastPageLi.addClass("disabled");
            } else {
                nextPageLi.click(function() {
                    to_page(result.extend.pageInfo.pageNum + 1);
                });
                lastPageLi.click(function() {
                    to_page(result.extend.pageInfo.pages);
                });
            }

            //1.添加首頁(yè)和前一頁(yè)
            ul.append(firstPageLi).append(prePageLi);
            $.each(result.extend.pageInfo.navigatepageNums, function(index,
                    item) {
                var numLi = $("<li></li>").append(
                        $("<a></a>").append(item).attr("href", "#"));
                if (result.extend.pageInfo.pageNum == item) {
                    numLi.addClass("active");
                }
                //添加點(diǎn)擊事件
                numLi.click(function() {
                    to_page(item);//點(diǎn)擊以后發(fā)送Ajax請(qǐng)求到當(dāng)前點(diǎn)擊的頁(yè)碼
                });
                //2.遍歷添加頁(yè)碼
                ul.append(numLi);
            });
            //3.遍歷完成后添加下一頁(yè)和末頁(yè)
            ul.append(nextPageLi).append(lastPageLi);
            //4.吧ul加入到nav
            var navEle = $("<nav></nav>").append(ul);
            navEle.appendTo("#page_nav_area");
        }

        //該方法用于重置表單彈出時(shí)上一次輸入的內(nèi)容以及校驗(yàn)的狀態(tài)
        function reset_form(ele) {
            $(ele)[0].reset();//重置表單內(nèi)容
            //清空樣式
            $(ele).find("*").removeClass("has-success has-error");
            $(ele).find(".help-block").text("");
        }
        //點(diǎn)擊新增按鈕彈出模態(tài)框
        $("#emp_add_modal_btn").click(function() {
            //表單完整重置(重置表單的樣式和內(nèi)容)
            reset_form("#empAddModal form");
            //發(fā)送Aajx請(qǐng)求查詢(xún)部門(mén)信息,顯示在下拉列表中
            getDepts("#empAddModal select");

            //彈出模態(tài)框
            $("#empAddModal").modal({
                backdrop : "static"
            });
        });

        //查出所有部門(mén)的信息并顯示在下拉列表中
        function getDepts(ele) {
            $(ele).empty();
            $.ajax({
                type : "GET",
                url : "${APP_PATH }/depts",
                success : function(result) {
                    //alert(msg.code);
                    //console.log(result);
                    $.each(result.extend.depts, function() {
                        var optionEle = $("<option></option>").append(
                                this.deptName).attr("value", this.deptId);
                        optionEle.appendTo(ele);
                    });

                }
            });
        }

        /**
         *添加員工表單前端校驗(yàn)函數(shù)
         */
        function validate_add_form() {
            //1.首先獲取輸入框中輸入的值
            var empName = $("#emp_add_input").val();
            var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
            if (!regName.test(empName)) {
                //alert("用戶(hù)名可以是2-5位中文或者6-16位英文和數(shù)字的組合");
                show_validate_msg("#emp_add_input", "error",
                        "用戶(hù)名可以是2-5位中文或者6-16位英文和數(shù)字的組合");
                return false;
            } else {
                show_validate_msg("#emp_add_input", "success", "");
            }
            ;

            //2.郵箱校驗(yàn)
            var email = $("#email_add_input").val();
            var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
            if (!regEmail.test(email)) {
                //alert("郵箱格式不正確");
                //清空元素之前的樣式
                show_validate_msg("#email_add_input", "error", "郵箱格式不正確");
                /* $("#email_add_input").parent().addClass("has-error");
                $("#email_add_input").next("span").text("郵箱格式不正確"); */
                return false;
            } else {
                show_validate_msg("#email_add_input", "success", "");
                /* $("#email_add_input").parent().addClass("has-success");
                $("#email_add_input").next("span").text(""); */
            }

            return true;
        }

        function show_validate_msg(ele, status, msg) {
            //清除當(dāng)前元素狀態(tài)
            $(ele).parent().removeClass("has-success has-error");
            $(ele).next("span").text("");
            if ("success" == status) {
                $(ele).parent().addClass("has-success");
                $(ele).next("span").text(msg);
            } else if ("error" == status) {
                $(ele).parent().addClass("has-error");
                $(ele).next("span").text(msg);
            }
        }

        /**
         *發(fā)送Ajax請(qǐng)求校驗(yàn)用戶(hù)名是否重復(fù)
         **/
        $("#emp_add_input").change(
                function() {
                    //1.模態(tài)框中填寫(xiě)的表單數(shù)據(jù)驗(yàn)證后提交給服務(wù)器進(jìn)行保存
                    var empName = this.value;
                    $.ajax({
                        url : "${APP_PATH}/checkuser",
                        type : "POST",
                        data : "empName=" + empName,
                        success : function(result) {
                            if (result.code == 100) {
                                show_validate_msg("#emp_add_input", "success",
                                        "用戶(hù)名可用");
                                $("#emp_save_btn").attr("ajax-va", "success");
                            } else {
                                show_validate_msg("#emp_add_input", "error",
                                        result.extend.va_msg);
                                $("#emp_save_btn").attr("ajax-va", "error");
                            }
                        }
                    });

                });

        /**
         *點(diǎn)擊保存按鈕,保存員工
         **/
        $("#emp_save_btn").click(function() {
            //1.模態(tài)框中填寫(xiě)的表單數(shù)據(jù)驗(yàn)證后提交給服務(wù)器進(jìn)行保存
            if (!validate_add_form()) {
                return false;
            }
            //判斷之前的ajax用戶(hù)名校驗(yàn)是否成功,如果不成功則直接返回false
            if ($(this).attr("ajax-va") == "error") {
                return false;
            }
            //2.發(fā)送AJax請(qǐng)求保存員工
            $.ajax({
                url : "${APP_PATH}/emp",
                type : "POST",
                data : $("#empAddModal form").serialize(),
                success : function(result) {
                    if (result.code == 100) {
                        //員工保存成功后:
                        //1.關(guān)閉模態(tài)框
                        $('#empAddModal').modal('hide');
                        //2.來(lái)到最后一頁(yè),顯示插入的數(shù)據(jù)
                        //發(fā)送ajax請(qǐng)求顯示最后一頁(yè)數(shù)據(jù)即可
                        to_page(totalRecord);

                    } else {
                        //顯示失敗信息
                        //有那個(gè)字段得錯(cuò)誤信息就顯示那個(gè)字段的
                        alert(result.extend.errorFields.email);
                        alert(result.extend.errorFields.empName);
                    }

                }
            });

        });

        //給編輯按鈕綁定事件(新版本得jquery中沒(méi)有l(wèi)ive方法轉(zhuǎn)而替換得是on方法)
        $(document).on("click", ".edit_btn", function() {
            //0.查出部門(mén)信息并顯示部門(mén)列表
            getDepts("#empUpdateModal select");
            //1.查出員工信息并顯示員工信息
            getEmp($(this).attr("edit-id"));
            //2.把員工id的值傳遞給模態(tài)框的更新按鈕
            $("#emp_update_btn").attr("edit-id", $(this).attr("edit-id"));
            //顯示模態(tài)框
            $("#empUpdateModal").modal({
                backdrop : "static"
            });
        });

        function getEmp(id) {
            $.ajax({
                url : "${APP_PATH}/emp/" + id,
                type : "GET",
                success : function(result) {
                    var empData = result.extend.emp;
                    $("#empName_update_static").text(empData.empName);
                    $("#email_update_input").val(empData.email);
                    $("#empUpdateModal input[name=gender]").val(
                            [ empData.gender ]);
                    $("#empUpdateModal select").val([ empData.dId ]);
                }
            });
        }

        //為員工更新按鈕綁定一個(gè)點(diǎn)擊事件
        $("#emp_update_btn").click(function() {
            //0.首先校驗(yàn)郵箱
            var email = $("#email_update_input").val();
            var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
            if (!regEmail.test(email)) {
                show_validate_msg("#email_update_input", "error", "郵箱格式不正確");
                return false;
            } else {
                show_validate_msg("#email_update_input", "success", "");
            }
            //1.發(fā)送Ajax請(qǐng)求,保存更新后的員工數(shù)據(jù)
            $.ajax({
                url : "${APP_PATH}/emp/" + $(this).attr("edit-id"),
                type : "PUT",
                data : $("#empUpdateModal form").serialize(),//+"&_method=PUT" 表單序列話(huà)后加上該字符串的意思是,將普通的POST請(qǐng)求轉(zhuǎn)換為PUT請(qǐng)求
                success : function(result) {
                    //alert(result.msg);
                    //1.關(guān)閉模態(tài)框
                    $("#empUpdateModal").modal("hide");
                    //2.回到本頁(yè)面
                    to_page(currentPage);
                }
            });
        });

        //單個(gè)刪除
        //為刪除按鈕綁定單擊事件(類(lèi)似于編輯按鈕綁定事件)
        $(document).on("click", ".delete_btn", function() {
            //彈出是否刪除確認(rèn)對(duì)話(huà)框
            var empName = $(this).parents("tr").find("td:eq(2)").text();
            var empId = $(this).attr("del-id");
            //alert($(this).parents("tr").find("td:eq(1)").text());
            if (confirm("確認(rèn)刪除【" + empName + "】嗎?")) {
                //確認(rèn),發(fā)送ajax請(qǐng)求刪除即可
                $.ajax({
                    url : "${APP_PATH}/emp/" + empId,
                    type : "DELETE",
                    success : function(result) {
                        alert(result.msg);
                        //處理成功后回到本頁(yè)
                        to_page(currentPage);
                    }
                });
            }
        });

        //完成全選/全不選功能
        $("#check_all").click(function() {
            //$(".check_item")
            $(".check_item").prop("checked", $(this).prop("checked"));
        });

        //check_item
        $(document)
                .on(
                        "click",
                        ".check_item",
                        function() {
                            var flag = $(".check_item:checked").length == $(".check_item").length;
                            $("#check_all").prop("checked", flag);
                        });

        //點(diǎn)擊全部刪除,批量刪除
        $("#emp_delete_all_btn").click(
                function() {
                    var empNames = "";
                    var empIds = "";
                    //遍歷選中的checkbox
                    $.each($(".check_item:checked"), function() {
                        empNames += $(this).parents("tr").find("td:eq(2)")
                                .text()
                                + ",";
                        empIds += $(this).parents("tr").find("td:eq(1)").text()
                                + "-";
                    });
                    empNames = empNames.substring(0, empNames.length - 1);
                    empIds = empIds.substring(0, empIds.length - 1);
                    if (confirm("確認(rèn)刪除【" + empNames + "】嗎?")) {
                        //發(fā)送ajax請(qǐng)求刪除
                        $.ajax({
                            url : "${APP_PATH}/emp/" + empIds,
                            type : "DELETE",
                            success : function(result) {
                                alert(result.msg);
                                //回到當(dāng)前頁(yè)
                                to_page(currentPage);
                            }
                        });
                    }

                });
        //點(diǎn)擊全部刪除,批量刪除
        $("#dep_search").click(function() {
                
                var key=$("#input_search").val();
                
                if(key==null||key==""){
                    alert(key);
                
                }else{

                    //發(fā)送ajax請(qǐng)求刪除
                    $.ajax({
                            url : "${APP_PATH}/emp/" + key,
                            type : "GET",
                            success : function(result) {
                                //1.解析并顯示員工數(shù)據(jù)
                                build_emps_table(result);
                                //2.解析并顯示分頁(yè)信息
                                build_page_info(result);
                                //3.解析并顯示分頁(yè)條
                                build_page_nav(result);
                            }
                        });
                    }
        });

    
        
        </script>
</body>
</html>


8. pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.hsun</groupId>
        <artifactId>spring</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>ssm-demo</artifactId>
    <packaging>war</packaging>


    <!-- 引入項(xiàng)目依賴(lài)的jar包 -->
    <dependencies>

        <!--日志 -->
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>

        <!-- 引入pageHelper分頁(yè)插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.0.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
        <!-- MBG -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>

        <!-- 引入Spring SpringMVC -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!-- 引入Spring test -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.7.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- 引入spring-jdbc(事物控制) -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!-- Spring面向切面編程 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!-- 引入mybatis -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>


        <!-- 引入mybatis整合Spring的適配包 -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- 數(shù)據(jù)庫(kù)連接池 -->
        <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <!-- mysql驅(qū)動(dòng) -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.42</version>
        </dependency>


        <!-- jstl servlet-api junit -->
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- Json數(shù)據(jù)格式依賴(lài)包 -->
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8</version>
        </dependency>
        <!-- JSR303數(shù)據(jù)校驗(yàn)支持,Tomcat7及以上的服務(wù)器直接在項(xiàng)目中導(dǎo)入jar包即可,tomcat及以下的 服務(wù)器需要額外的給服務(wù)器中的lib包中替換新標(biāo)準(zhǔn)的el表達(dá)jar包 -->
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.4.1.Final</version>
        </dependency>

        <!-- commons -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>

    <!-- <build> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> 
        <version>3.0.0</version> </plugin> </plugins> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
        <failOnMissingWebXml>false</failOnMissingWebXml> </properties> <failOnMissingWebXml>false</failOnMissingWebXml> -->
</project>

源碼查看

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,565評(píng)論 6 539
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,115評(píng)論 3 423
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事?!?“怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 177,577評(píng)論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 63,514評(píng)論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,234評(píng)論 6 410
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 55,621評(píng)論 1 326
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,641評(píng)論 3 444
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 42,822評(píng)論 0 289
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,380評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,128評(píng)論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,319評(píng)論 1 371
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,879評(píng)論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,548評(píng)論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 34,970評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 36,229評(píng)論 1 291
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,048評(píng)論 3 397
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,285評(píng)論 2 376

推薦閱讀更多精彩內(nèi)容