SSM-CRUD

在这里插入图片描述在这里插入图片描述在这里插入图片描述

MyBatis逆向工程

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
  
  <context id="DB2Tables" targetRuntime="MyBatis3">
  	<commentGenerator>
		<property name="suppressAllComments" value="true" />
	</commentGenerator>
  	<!-- 配置数据库连接 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/ssm_crud"
        userId="root"
        password="123">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

	<!-- 指定javaBean 的生成方式 -->
	<javaModelGenerator targetPackage="it.bean"
		targetProject=".\src\main\java">
		<property name="enableSubPackages" value="true" />
		<property name="trimStrings" value="true" />
	</javaModelGenerator>
	<!-- 指定sql映射文件的生成位置 -->
    <sqlMapGenerator targetPackage="mapper"  
    	targetProject=".\src\main\resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

	<!-- 指定dao接口生成的位置,mapper接口 -->
    <javaClientGenerator type="XMLMAPPER" 
    	targetPackage="it.dao" 
    	targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

	<table tableName="employees" domainObjectName="Employee"></table>
	<table tableName="department" domainObjectName="Department"></table>
  </context>
</generatorConfiguration>


package it.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MBGTest {
	
	public static void main(String[] args) throws Exception {
		   List<String> warnings = new ArrayList<String>();
		   boolean overwrite = true;
		   File configFile = new File("mbg.xml");
		   ConfigurationParser cp = new ConfigurationParser(warnings);
		   Configuration config = cp.parseConfiguration(configFile);
		   DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		   MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		   myBatisGenerator.generate(null);
	}
}

applicationContext.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:aop="http://www.springframework.org/schema/aop"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">

	<!-- 自动扫描,除了Controller 不扫描,其他都要扫描 -->
	<context:component-scan base-package="it">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>

	<!-- Spring的配置文件,这里主要配置和业务逻辑有关的 -->
	<!-- 数据源,事务控制,xxx -->
	
	<context:property-placeholder location="classpath:dbconfig.properties"/>
	
	<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>

	<!-- 配置MyBatis的整合 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 指定mybatis全局配置文件的位置 -->
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>
		<property name="dataSource" ref="pooledDataSource"></property>
		<!-- 指定mybatis,mapper文件的位置 -->
		<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
	</bean>
	
	<!-- 配置扫描器,将MyBatis接口的实现加入到IOC 容器中 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 扫描所有的dao接口的实现,加入到IOC 容器中 -->
		<property name="basePackage" value="it"></property>
	</bean>
	
	<!-- 设置一个可以执行批量的SQLSession(MapperTest类中使用批量添加员工) -->
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> 
		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
		<constructor-arg name="executorType" value="BATCH"></constructor-arg>
	</bean>
	
	<!-- 事务控制的配置 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 控制事务管理器 -->
		<property name="dataSource" ref="pooledDataSource"></property>
	</bean>
	
	<!-- 开启基于注解的事务,或者使用xml配置形式的事务(必要和主要的事务都采取配置xml的形式) -->
	<aop:config>
		 <!-- 配置切入点表达式 -->
		 <aop:pointcut expression="execution(* it.service..*(..))" id="txPoint"/>
		 <!-- 配置事务增强 -->
		 <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
	</aop:config>
	
	<!-- 配置事务增强,事务如何加入 -->
	<tx:advice id="txAdvice">
		<tx:attributes>
			<!-- 所有方法都是事务方法 -->
			<tx:method name="*"/>
			<!-- 所有的get开始的方法都是事务方法 -->
			<tx:method name="get*" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- Spring配置文件的核心点: 数据源,与MyBatis的整合,事务控制 -->
</beans>

MyBatis-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"></setting>
 	</settings>
 
 	<!-- 给对应包下起别名 -->
 	<typeAliases>
 		<package name="it.bean"/>
 	</typeAliases>
 	
 	<!-- 引入分页插件 -->
 	<plugins>
 		<plugin interceptor="com.github.pagehelper.PageInterceptor">
 			<property name="reasonable" value="true"/>
 		</plugin>
 		
 	</plugins>
 </configuration>

controller层

package it.controller;

import it.bean.Employee;
import it.bean.Msg;
import it.dao.EmployeeMapper;
import it.servlet.EmployeeService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;

/**
 * 处理员工的CRUD 请求
 * 
 * @author lenovo
 * 
 */
@Controller
public class EmployeeController {

	@Autowired
	EmployeeService employeeService;
	
	@RequestMapping("/success")
	public String test() {
		return "success";
	}
	
	/*
	 * 单个,批量
	 * 
	 */
	@RequestMapping(value="/emp/{ids}",method=RequestMethod.DELETE)
	@ResponseBody
	public Msg deleteEmp(@PathVariable("ids")String ids) {
		//区分一下, 批量删除, 和单个删除
		if(ids.contains("-")) {
			String[] strings = ids.split("-");
			List<Integer> list = new ArrayList<Integer>();
			for (String str : strings) {
				list.add(Integer.parseInt(str));
			}
			employeeService.deleteEmps(list);
		}else {
			Integer id = Integer.parseInt(ids);
			employeeService.deleteEmployee(id);
		}
			
		return Msg.success();
	}
	
	/**
	 * 1,如果直接发送ajax = PUT形式的请求
	 * 封装数据
	 * Employee 除empId,其他值全是NULL
	 * 问题: 请求有数据,但是Employee对象封装不上,SQL语句出错
	 * 
	 * 原因: Tomcat 
	 * 			1,将请求体的数据封装成一个map
	 * 			2,request.getParameter("empName")就会从这个Map中获取对象;
	 * 			3,SpringMVC 封装成POJO对象的时候,
	 * 				会把POJO对象的每一个属性的值,会把request.getParamter("empName");
	 * 
	 * AJAX 发送PUT请求引发的血案:
	 * 		PUT请求:请求体中的数据:request.getParameter("empName")拿不到
	 * 		是因为 Tomcat 一看是PUT 不会封装请求体为map,只有POST请求才封装请求体为map
	 * 解决方案:
	 * 我们要能支持直接发送PUT请求之类的请求还要封装请求体中的数据,
	 * 1,配置上HttpPUTFormContentFilter,
	 * 2,他的作用,将请求体中的数据解析包装成一个map
	 * 3,request被重新包装,request.getParameter() 被重写,就会从自己封装的map中获取,
	 * @param employee
	 * @return
	 */
	@RequestMapping(value="/emp/{empId}",method=RequestMethod.PUT)
	@ResponseBody
	public Msg updateEmployee(Employee employee) {
		System.out.println("将要更新的员工: "+employee);
		employeeService.updateEmployee(employee);
		return Msg.success();
	}
	
	//根据id,查询员工 ,@PathVariable 表示从地址中获取参数
	@RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
	@ResponseBody
	public Msg getEmpId(@PathVariable("id")Integer id) {
		Employee employee = employeeService.getEmpId(id);
		return Msg.success().addAttribute("employee", employee);
	}
	
	//检查员工名是否重复
	@RequestMapping("/chuckUserName")
	@ResponseBody
	public Msg chuckUserName(@RequestParam("empName") String empName) {
		//首先判断用户名是否合法
		String reg = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})";
		if(!empName.matches(reg)) {
			return Msg.fail().addAttribute("error", "用户名英文字母个数6-16,汉字2-5个");
		}
		//查询数据库, 首先先进行验证
		boolean b = employeeService.chuckUserName(empName);
		if(b) {
			return Msg.success();			
		}else {
			return Msg.fail().addAttribute("error", "用户名不可用");
		}
	}
	
	
	/**
	 * 员工保存
	 * @Valid 表示封装以后的数据要进行校验
	 * BuindingResult 表示校验成功或者失败
	 * @param employee
	 * @return
	 */
	@RequestMapping(value="/emp",method=RequestMethod.POST)
	@ResponseBody
	public Msg saveEmp(@Valid Employee employee,BindingResult result) {
		//result.hasErros 表示校验成功或者失败
		Map<String,Object> map = new HashMap<String, Object>();
		if(result.hasErrors()) {
			//校验失败,应该返回失败,在模态框中显示校验失败的错误消息
			List<FieldError> list =	result.getFieldErrors();
			for (FieldError fieldError : list) {
				map.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			return Msg.fail().addAttribute("errorFields", map);
		}else {
			employeeService.saveEmp(employee);
			return Msg.success();			
		}
	}

	/**
	 * 需要导入jackson 包
	 * @param pn
	 * @return
	 */
	//该注解的作用是将返回值,自动分装成json 串 :@ResponseBody
	@RequestMapping("/emps")
	@ResponseBody	
	public Msg getEemployeesWithJSON(
			@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
		// 引入PageHelper 分页插件
		// 在查询之前只需调用,.插入页面,以及每页的记录数
		PageMethod.startPage(pn, 3);
		// startPage 后面紧跟的这个查询就是一个分页查询
		List<Employee> list = employeeService.getEmployees();
		
		// 使用pageInfo包装查询的结果.只需要将pageInfo交给页面就行了
		// 封装详细的分页信息,包括我们查询出来的数据,5: 表示连续显示的5页
		PageInfo page = new PageInfo(list, 5);
		
		Msg msg = Msg.success();
		
		msg.addAttribute("pageInto", page);
		
		return msg;
	}

	/*
	 * 查询员工数据,(分页查询)
	 * 
	 * @RequestParam(value="pn",defaultValue="1") Integer pn :pn
	 * 表示分页查询,不传入值,默认值为1
	 */
	//@RequestMapping("/emps")
	public String getEemployees(
			@RequestParam(value = "pn", defaultValue = "1") Integer pn,
			Model model) {
		// 引入PageHelper 分页插件
		// 在查询之前只需调用,.插入页面,以及每页的记录数
		PageMethod.startPage(pn, 3);
		System.out.println("a");
		// startPage 后面紧跟的这个查询就是一个分页查询
		List<Employee> list = employeeService.getEmployees();
		
		// 使用pageInfo包装查询的结果.只需要将pageInfo交给页面就行了
		// 封装详细的分页信息,包括我们查询出来的数据,5: 表示连续显示的5页
		PageInfo page = new PageInfo(list, 5);
		
		model.addAttribute("pageInfo", page);
		return "list";
	}
}

package it.controller;

import it.bean.Department;
import it.bean.Msg;
import it.servlet.DepartmentService;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 处理有关部门的操作
 * 
 */
@Controller
public class DepartmentController {

	@Autowired
	private DepartmentService departmentService;
	
	@RequestMapping("/depts")
	@ResponseBody
	public Msg getDepts() {
		List<Department> list =  departmentService.getDepartments();
	
		return Msg.success().addAttribute("depts",list);	
	}
	
}

service层

package it.servlet;

import it.bean.Employee;
import it.bean.EmployeeExample;
import it.bean.EmployeeExample.Criteria;
import it.dao.EmployeeMapper;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {
	
	@Autowired
	EmployeeMapper employeeMapper;
	
	//查询所有员工没有条件
	public List<Employee> getEmployees() {
		return employeeMapper.selectByExampleDepartment(null);
	}

	public void saveEmp(Employee employee) {
		employeeMapper.insertSelective(employee);
		
	}

	/*
	 * 检查用户 名是否可用
	 * count 表示记录数为零时,记录数可用
	 */
	public boolean chuckUserName(String empName) {
		//根据条件查询
		EmployeeExample example = new EmployeeExample();
		Criteria criteria = example.createCriteria();
		criteria.andEmpNameEqualTo(empName);
		long count = employeeMapper.countByExample(example);
		return count == 0;
	}

	public Employee getEmpId(Integer id) {
		Employee employee = employeeMapper.selectByPrimaryKey(id);
		return employee;
	}

	public void updateEmployee(Employee employee) {
		employeeMapper.updateByPrimaryKeySelective(employee);
		
	}

	public void deleteEmployee(Integer id) {
		employeeMapper.deleteByPrimaryKey(id);
		
	}

	public void deleteEmps(List<Integer> strings) {
		EmployeeExample example = new EmployeeExample();
		Criteria criteria = example.createCriteria();
		
		//sql 语句就变成 delete from xxx where emp_id in(...)
		criteria.andEmpIdIn(strings);
		
		employeeMapper.deleteByExample(example);
	}
}

package it.servlet;

import it.bean.Department;
import it.dao.DepartmentMapper;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DepartmentService {

	@Autowired
	private DepartmentMapper departmentMapper;
	
	public List<Department> getDepartments() {
		return departmentMapper.selectByExample(null);
	}

	
}

DAO层

package it.dao;

import it.bean.Employee;
import it.bean.EmployeeExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

@Service
public interface EmployeeMapper {
    long countByExample(EmployeeExample example);

    int deleteByExample(EmployeeExample example);

    int deleteByPrimaryKey(Integer empId);

    int insert(Employee record);

    int insertSelective(Employee record);

    List<Employee> selectByExample(EmployeeExample example);

    Employee selectByPrimaryKey(Integer empId);
    
    List<Employee> selectByExampleDepartment(EmployeeExample example);

    Employee selectByPrimaryKeyDepartment(Integer empId);

    int updateByExampleSelective(@Param("record") Employee record, @Param("example") EmployeeExample example);

    int updateByExample(@Param("record") Employee record, @Param("example") EmployeeExample example);

    int updateByPrimaryKeySelective(Employee record);

    int updateByPrimaryKey(Employee record);

	
}
package it.dao;

import it.bean.Department;
import it.bean.DepartmentExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

@Service
public interface DepartmentMapper {
    long countByExample(DepartmentExample example);

    int deleteByExample(DepartmentExample example);

    int deleteByPrimaryKey(Integer depId);

    int insert(Department record);

    int insertSelective(Department record);

    List<Department> selectByExample(DepartmentExample example);

    Department selectByPrimaryKey(Integer depId);

    int updateByExampleSelective(@Param("record") Department record, @Param("example") DepartmentExample example);

    int updateByExample(@Param("record") Department record, @Param("example") DepartmentExample example);

    int updateByPrimaryKeySelective(Department record);

    int updateByPrimaryKey(Department record);
}

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="it.dao.EmployeeMapper">
  <resultMap id="BaseResultMap" type="it.bean.Employee">
    <id column="emp_id" jdbcType="INTEGER" property="empId" />
    <result column="emp_name" jdbcType="VARCHAR" property="empName" />
    <result column="emp_gender" jdbcType="VARCHAR" property="empGender" />
    <result column="emp_email" jdbcType="VARCHAR" property="empEmail" />
    <result column="dep_id" jdbcType="INTEGER" property="depId" />
  </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, emp_gender, emp_email, dep_id
  </sql>
  <!-- 添加员工加部门的查询 -->
  <!--  List<Employee> selectByExampleDepartment(EmployeeExample example); -->
  <select id="selectByExampleDepartment" parameterType="it.bean.EmployeeExample" resultMap="WithDepartmentResultMap">
  	select
    <if test="distinct">
      distinct
    </if>
    <include refid="WithDepartment_Column_List" />
    from employees e
    left join department d on e.dep_id = d.dep_id
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <sql id="WithDepartment_Column_List">
  	e.emp_id,e.emp_name,emp_gender,emp_email,e.dep_id,d.dep_id,d.dep_name
  </sql>
  <resultMap type="it.bean.Employee" id="WithDepartmentResultMap">
  	<id column="emp_id" jdbcType="INTEGER" property="empId" />
    <result column="emp_name" jdbcType="VARCHAR" property="empName" />
    <result column="emp_gender" jdbcType="VARCHAR" property="empGender" />
    <result column="emp_email" jdbcType="VARCHAR" property="empEmail" />
    <result column="dep_id" jdbcType="INTEGER" property="depId" />
    
    <!-- 查询员工的部门信息 -->
    <association property="department" javaType="it.bean.Department">
    	<id column="dep_id" property="depId"/>
    	<result column="dep_name" property="depName"/>
    </association>
  </resultMap>
  <!-- Employee selectByPrimaryKeyDepartment(Integer empId); -->
  <select id="selectByPrimaryKeyDepartment" parameterType="java.lang.Integer" resultMap="WithDepartmentResultMap">
    select 
    <include refid="WithDepartment_Column_List" />
    from employees e
    left join department d on e.dep_id = d.dep_id
    where emp_id = #{empId,jdbcType=INTEGER}
  </select>
  
  <select id="selectByExample" parameterType="it.bean.EmployeeExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from employees
    <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 employees
    where emp_id = #{empId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from employees
    where emp_id = #{empId,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="it.bean.EmployeeExample">
    delete from employees
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="it.bean.Employee">
    insert into employees (emp_id, emp_name, emp_gender, 
      emp_email, dep_id)
    values (#{empId,jdbcType=INTEGER}, #{empName,jdbcType=VARCHAR}, #{empGender,jdbcType=VARCHAR}, 
      #{empEmail,jdbcType=VARCHAR}, #{depId,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="it.bean.Employee">
    insert into employees
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="empId != null">
        emp_id,
      </if>
      <if test="empName != null">
        emp_name,
      </if>
      <if test="empGender != null">
        emp_gender,
      </if>
      <if test="empEmail != null">
        emp_email,
      </if>
      <if test="depId != null">
        dep_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="empGender != null">
        #{empGender,jdbcType=VARCHAR},
      </if>
      <if test="empEmail != null">
        #{empEmail,jdbcType=VARCHAR},
      </if>
      <if test="depId != null">
        #{depId,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="it.bean.EmployeeExample" resultType="java.lang.Long">
    select count(*) from employees
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update employees
    <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.empGender != null">
        emp_gender = #{record.empGender,jdbcType=VARCHAR},
      </if>
      <if test="record.empEmail != null">
        emp_email = #{record.empEmail,jdbcType=VARCHAR},
      </if>
      <if test="record.depId != null">
        dep_id = #{record.depId,jdbcType=INTEGER},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update employees
    set emp_id = #{record.empId,jdbcType=INTEGER},
      emp_name = #{record.empName,jdbcType=VARCHAR},
      emp_gender = #{record.empGender,jdbcType=VARCHAR},
      emp_email = #{record.empEmail,jdbcType=VARCHAR},
      dep_id = #{record.depId,jdbcType=INTEGER}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="it.bean.Employee">
    update employees
    <set>
      <if test="empName != null">
        emp_name = #{empName,jdbcType=VARCHAR},
      </if>
      <if test="empGender != null">
        emp_gender = #{empGender,jdbcType=VARCHAR},
      </if>
      <if test="empEmail != null">
        emp_email = #{empEmail,jdbcType=VARCHAR},
      </if>
      <if test="depId != null">
        dep_id = #{depId,jdbcType=INTEGER},
      </if>
    </set>
    where emp_id = #{empId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="it.bean.Employee">
    update employees
    set emp_name = #{empName,jdbcType=VARCHAR},
      emp_gender = #{empGender,jdbcType=VARCHAR},
      emp_email = #{empEmail,jdbcType=VARCHAR},
      dep_id = #{depId,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="it.dao.DepartmentMapper">
  <resultMap id="BaseResultMap" type="it.bean.Department">
    <id column="dep_id" jdbcType="INTEGER" property="depId" />
    <result column="dep_name" jdbcType="VARCHAR" property="depName" />
  </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">
    dep_id, dep_name
  </sql>
  <select id="selectByExample" parameterType="it.bean.DepartmentExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from department
    <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 department
    where dep_id = #{depId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from department
    where dep_id = #{depId,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="it.bean.DepartmentExample">
    delete from department
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="it.bean.Department">
    insert into department (dep_id, dep_name)
    values (#{depId,jdbcType=INTEGER}, #{depName,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="it.bean.Department">
    insert into department
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="depId != null">
        dep_id,
      </if>
      <if test="depName != null">
        dep_name,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="depId != null">
        #{depId,jdbcType=INTEGER},
      </if>
      <if test="depName != null">
        #{depName,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="it.bean.DepartmentExample" resultType="java.lang.Long">
    select count(*) from department
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update department
    <set>
      <if test="record.depId != null">
        dep_id = #{record.depId,jdbcType=INTEGER},
      </if>
      <if test="record.depName != null">
        dep_name = #{record.depName,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update department
    set dep_id = #{record.depId,jdbcType=INTEGER},
      dep_name = #{record.depName,jdbcType=VARCHAR}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="it.bean.Department">
    update department
    <set>
      <if test="depName != null">
        dep_name = #{depName,jdbcType=VARCHAR},
      </if>
    </set>
    where dep_id = #{depId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="it.bean.Department">
    update department
    set dep_name = #{depName,jdbcType=VARCHAR}
    where dep_id = #{depId,jdbcType=INTEGER}
  </update>
</mapper>

SpringMVC

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

	<!--SpringMVC的配置文件,包含网站跳转逻辑的控制,配置  -->
	<context:component-scan base-package="it" use-default-filters="false">
		<!--只扫描控制器。  -->
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	
	<!--配置视图解析器,方便页面返回  -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<!--两个标准配置  -->
	<!-- 将springmvc不能处理的请求交给tomcat -->
	<mvc:default-servlet-handler/>
	<mvc:view-controller path="/list" view-name="list"/>
	<!-- 能支持springmvc更高级的一些功能,JSR303校验,快捷的ajax...映射动态请求 -->
	<mvc:annotation-driven/>

</beans>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib  prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
pageContext.setAttribute("Path",request.getContextPath());
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>员工列表</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	
	<!-- 引入样式 -->
  	<script type="text/javascript" src="${Path }/static/js/jquery-1.12.4.min.js"></script>
	
	<!-- 引入样式 -->
    <link href="${Path }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="${Path }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
  </head>
  
  <body>
  		<!-- 员工修改的模态框 -->
		<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" 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">
				      <!-- 静态输入框 -->
				      <p class="form-control-static" id="empNameUpdateStatic"></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="empEmail" class="form-control" id="empEmail_update_input" placeholder="email@atguigu.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="empGender" id="gender1_update_input" value="1" checked="checked"></label>
						<label class="radio-inline">
						  <input type="radio" name="empGender" id="gender2_update_input" value="0"></label>
				    </div>
				  </div>
				  <div class="form-group">
				    <label class="col-sm-2 control-label">deptName</label>
				    <div class="col-sm-4">
				    	<!-- 部门提交部门id即可 -->
				      <select class="form-control" name="depId" >
				      </select>
				    </div>
				  </div>
				</form>
		      </div>
		      <div class="modal-footer">
		        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
		        <button type="button" class="btn btn-primary" id="emp_update_btn">修改</button>
		      </div>
		    </div>
		  </div>
		</div>
  		
		<!-- 员工添加的模态框 -->
		<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" name="empName" class="form-control" id="empName_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="empEmail" class="form-control" id="empEmail_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="empGender" id="gender1_add_input" value="0" checked="checked"></label>
						<label class="radio-inline">
						  <input type="radio" name="empGender" id="gender2_add_input" value="1"></label>
				    </div>
				  </div>
				  <div class="form-group">
				    <label class="col-sm-2 control-label">deptName</label>
				    <div class="col-sm-4">
				    	<!-- 部门提交部门id即可 -->
				      <select class="form-control" name="depId" >
				      </select>
				    </div>
				  </div>
				</form>
		      </div>
		      <div class="modal-footer">
		        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
		        <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
		      </div>
		    </div>
		  </div>
		</div>
  		
    	<!-- 搭建显示页面 -->
    	<div class="container">
    		<!-- 第一行: 标题 -->
    		<div class="row">
    			<div class="col-md-12">
    				<h1>员工表(SSM-CRUD)</h1>
    			</div> <!-- 表示标题占12-->
    		</div>
    		<!-- 第二行: 按钮 -->
    		<div class="row">
    			<div class="col-md-4 col-md-offset-8">
    				<button class="btn btn-primary" id="emp_add_model">新增</button>
 					<button class="btn btn-danger" id="emp_delete_all_btn">删除</button> 				
    			</div>
    		</div>
    		<!-- 第三行: 员工表格 -->
    		<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>姓名</th>
	    						<th>性别</th>
	    						<th>邮箱</th>
	    						<th>部门</th>
	    						<th>操作</th>
	    					</tr>
    					</thead>
    					<tbody>
    					
    					</tbody>
    				</table>
    			</div>
    		</div>
    		<!-- 显示分页信息 -->
    		<div class="row">
    			<!-- 分页文字信息 -->
    			<div class="col-md-6" id="page_info_area">
    				
    			</div>
    			<!-- 分页条信息 -->
    			<div class="col-md-6" id="page_nav_area">
					
    			</div>
    		</div>
    	</div>
    	 
    	<script type="text/javascript">
    		var totalRecord; //用于添加用户时,获取总页面数,进行跳转到最后一页
    	 	var currentPage; //表示当前页面
    		//1,页面加载完成后,直接去发送一个ajax请求,要到分页数据
    		$(function(){
    			//去首页
    			to_page(1);
    		});
    		
    		function to_page(pn) {
    			$.ajax({
    				url:"${Path }/emps",
    				data:"pn=" + pn,
    				type:"GET",
    				success:function(result) {
    					//console.log(result);
    					//1,解析并显示员工信息
    					build_emps_table(result);
    					//2,显示页码信息
    					build_page_info(result);
    					//2,解析并显示分页信息
    					build_page_nav(result);
    					
    				}
    			});
    		}
    		
    		function build_emps_table(result) {
    			//清空table表格
    			$("#emps_table tbody").empty();
    			
    			var emps = result.ma.pageInto.list;
    			//遍历员工
    			$.each(emps,function(index,item) {
    				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.empGender == "1" ? "男" : "女");
    				var deptNameTd = $("<td></td>").append(item.department.depName);
    				var emailTd = $("<td></td>").append(item.empEmail);
    				/*<button class="btn btn-primary btn-sm">
	    								<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
	    								编辑
	    							</button>
	    							<button class="btn btn-danger btn-sm">
	    								<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
	    								删除
	    							</button>*/
    				var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
    									.append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("修改");
	    			//添加一个自定义的属性,用于员工修改操作时,根据id,获取员工
	    			editBtn.attr("emp_edit_id",item.empId);
	    			var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
									.append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
	    			//当删除按钮添加一个自定义的属性表示当前删除的员工的id
	    			delBtn.attr("del-id",item.empId);
	    			var btnTd = $("<tb></tb>").append(editBtn).append(delBtn);
    				//append 方法执行完成以后,还是返回原来的元素
    				$("<tr></tr>").append(checkBoxTd)
    								.append(empIdTd)
    								.append(empNameTd)
    								.append(genderTd)
    								.append(emailTd)
    								.append(deptNameTd)
    								.append(btnTd)
    								.appendTo("#emps_table tbody");
    			});
    		}
    		
    		//解析显示分页信息
    		function build_page_info(result) {
    			$("#page_info_area").empty();
    			$("#page_info_area").append("当前" + result.ma.pageInto.pageNum + "页,总共"+ 
    									result.ma.pageInto.pages+"页,总共"+result.ma.pageInto.total+"条记录");
    			totalRecord = result.ma.pageInto.total;
    			currentPage = result.ma.pageInto.pageNum;
    		}
    		
    		//解析显示分页条
    		function build_page_nav(result) {
    			//page_nav_area
    			
    			$("#page_nav_area").empty();
    			
    			var ul = $("<ur></ur>").addClass("pagination"); 
    			
    			var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#")); //设置首页
    			var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;")); //设置前一页
    			if(result.ma.pageInto.hasPreviousPage == false) {	//当没有前一页,赋值一个disabled
    				firstPageLi.addClass("disabled");
    				prePageLi.addClass("disabled");
    			}else {
	    			//为元素添加点击翻页事件
	    			firstPageLi.click(function() {
	    				to_page(1);
	    			});
	    			prePageLi.click(function() {
	    				to_page(result.ma.pageInto.pageNum-1);
	    			});
    				
    			}
    			//添加首页,上一页提示
    			ul.append(firstPageLi).append(prePageLi);
    			
  				var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;")); //设置后一页		
    			var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"));	  //设置末页
    			if(result.ma.pageInto.hasNextPage == false) {
    				nextPageLi.addClass("disabled");
    				lastPageLi.addClass("disabled");
    			}else {
	    			//为下一页,末页绑定点击事件
	    			nextPageLi.click(function() {
	    				to_page(result.ma.pageInto.pageNum+1);
	    			});
	    			lastPageLi.click(function() {
	    				to_page(result.ma.pageInto.pages);
	    			});
	    			//添加首页和前一页的提示
	    			ul.append(firstPageLi).append(prePageLi);
    			}
    			
    			$.each(result.ma.pageInto.navigatepageNums,function(index,item) {
    				var numLi =  $("<li></li>").append($("<a></a>").append(item));
    				//添加标识符
    				if(result.ma.pageInto.pageNum == item) {
    					numLi.addClass("active");
    				}
    				//绑定一个点击事件
    				numLi.click(function() {
    					to_page(item);
    				});
    				
    				
    				//添加页码
    				ul.append(numLi);
    			});
    			
    			//添加下一页和末页
    			ul.append(nextPageLi).append(lastPageLi);
    			
    			var navEle = $("<nav></nav>").append(ul);
    			navEle.appendTo("#page_nav_area");
    		}
    		//完整的清空表单样式,以及内容
    		function reset_form(ele) {
    			$(ele)[0].reset();
    			//清空表单样式
    			$(ele).find("*").removeClass("has-error has-success");
    			$(ele).find(".help-block").text("");
    		}
    		
    		//点击新增按钮, 弹出模态框
    		$("#emp_add_model").click(function() {
    			//清除表单数据(表单完整重置)
    			reset_form("#empAddModal form");
    			$("#empAddModal form")[0].reset();
    			
    			//发送ajax请求,查询部门信息显示在下拉列表中
    			getDepts("#empAddModal select");
    			//模态框弹出
    			$("#empAddModal").modal({
    				//向modal设置一些属性
    				backdrop:"static"
    				
    			});
    			
    		});
    		
    		//查询所有的部门信息, 并显示在下拉列表中
    		function getDepts(ele) {
    			 //清空下拉列表中的元素
    			$(ele).empty();
    			 $.ajax({
    				 url:"${Path}/depts",
    				 type:"GET",
    				 success:function(result) {
    					 //console.log(result);
    					 //$("#empAddModal select")
    					 $.each(result.ma.depts,function() {
    						 var optionEle = $("<option></option>").append(this.depName).attr("value",this.depId);
    						 optionEle.appendTo(ele);
    					 });
    				 }
    			 });
    		}
    		
    		//点击保存的方法
    		$("#emp_save_btn").click(function() {
    			//将模态框中填写的表单数据交给服务器进行保存
    			
    			//1,先对要提交给服务器的数据 进行校验(前端校验)
    			if(!validate_add_form()) {
    				return false;
    			}
    			//判断之前的ajax用户名校验是否成功
    			if($(this).attr("ajax-va") == "error") {
    				return false;
    			}
    			//2,发送ajax请求保存员工
    			$.ajax({
    				url:"${Path}/emp",
    				type:"POST",
    				data:$("#empAddModal form").serialize(),
    				success: function(result) {
    					//alert(result.str);
    					if(result.state == 100) {
	    					//员工保存成功
	    					//1,关闭模态框
	    					$("#empAddModal").modal("hide");
	    					//2,来到最后一页,显示刚才保存的数据
	    					//发送ajax请求,显示最后一页数据即可
	    					to_page(totalRecord);
    					}else {
    						//显示失败信息
    						//console.log(result);
    						//后端校验
    						if(underfined == result.ma.errorField.email) {
    							//显示邮箱的错误信息
    							show_validate_msg("#empEmail_add_input","error",result.ma.errorField.email);
    						}
    						if(underfined == result.ma.error.empName) {
    							//显示邮箱的错误信息
    							show_validate_msg("#empName_add_input","error",result.ma.error.empName);
    						} 
    					}
    				}
    			});
    		});
    		
    		//该方法用于数据提交表单数据校验
    		function validate_add_form() {
    			//1,拿到要校验的数据,使用正则表达式
    			//校验用户名
    			var empName = $("#empName_add_input").val();
    			var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;// /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/
    			///(^[a_zA_Z0_9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,6})/
    			if(!regName.test(empName)) {
    				//alert("用户名可以是2-6位的中文或者6-16位的英文和数字组合");
    				
    				show_validate_msg("#empName_add_input","error","用户名可以是2-6位的中文或者6-16位的英文和数字组合");
    				return false;
    			}else {
    				show_validate_msg("#empName_add_input","success","");
    				
    			}	
    			
    			//校验邮箱
    			var empEmail = $("#empEmail_add_input").val();
    			var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
    			if(!regEmail.test(empEmail)) {
 
    				//应该清空这个元素之前的格式
    				
    				show_validate_msg("#empEmail_add_input","error","邮箱格式错误");
    				
    				return false;
    			}else {
    				show_validate_msg("#empEmail_add_input","success","");
    				
    			}
    			return true;
    		}
    		
    		//
    		function show_validate_msg(ele,status,msg) {
    			//清除元素的状态,元素之间的格式
    			$(ele).parent().removeClass("has-success has-error");
    			$(ele).next("span").text("");
    			if("success" == status) {
    				$(ele).parent().addClass("has-success");
    				$(ele).next("span").text("");
    			}else if("error" == status) {
    				$(ele).parent().addClass("has-error");
    				$(ele).next("span").text(msg);
    			}
    		}
    		
    		//校验用户名是否可用
    		$("#empName_add_input").change(function() {
    			//发送ajax请求校验用户名是否可用
    			var empName = this.value;
    			$.ajax({
    				url:"${Path}/chuckUserName",
    				data:"empName="+empName,
    				type:"POST",
    				success: function(result) {
    					if(result.state == 100) {
    						show_validate_msg("#empName_add_input","success","");
    						$("#emp_save_btn").attr("ajax-va","success");
    					}else {
    						show_validate_msg("#empName_add_input","error",result.ma.error);
    						$("#emp_save_btn").attr("ajax-va","error");
    					}
    				}
    				
    				
    			});
    		});
    		
    		//1,我们是按钮创建之前绑定了click, 所以绑定不上,
    		//处理办法
    		//1),可以在创建按钮的时候绑定(耦合性太高). 2),绑定点击.live(推荐,但新的版本已删除了此方法,用on方法所代替)
    		$(document).on("click",".edit_btn",function() {
    			//alert("你好");
    			//1,查询出所有的部门
    			getDepts("#empUpdateModal select");
    			//2,查询出员工,回显到模态框中
    			getEmp($(this).attr("emp_edit_id"));
    			//3,把员工的id传递给模态框的更新按钮
    			$("#emp_update_btn").attr("emp_edit_id",$(this).attr("emp_edit_id"));
    			
    			//弹出模态框
    			$("#empUpdateModal").modal({
    				//向modal设置一些属性
    				backdrop:"static"
    				
    			});
    		});
    		
    		//ajax请求,根据id获取employee
    		function getEmp(id) {
    			$.ajax({
	    			url:"${Path}/emp/" + id,
	    			type:"GET",
	    			success: function(result) {
	    				var emp = result.ma.employee;
	    			
	    				//回显
	    				$("#empNameUpdateStatic").text(emp.empName);
	    				$("#empEmail_update_input").val(emp.empEmail);
	    				$("#empUpdateModal input[name=empGender]").val([emp.empGender]);
	    				$("#empUpdateModal select").val(emp.depId);
	    			}
    			});
    			
    			
    		}
    		
    		//点击更新按钮,更新员工信息
    		$("#emp_update_btn").click(function() {
    			//验证员工邮箱是否有效,
    			//1,校验员工邮箱
    			var empEmail = $("#empEmail_update_input").val();
    			var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
    			if(!regEmail.test(empEmail)) {
    				show_validate_msg("#empEmail_update_input","error","邮箱格式错误");	
    				return false;
    			}else {
    				show_validate_msg("#empEmail_update_input","success","");
    				
    			}
    			
    			//2.发送ajax请求保存更新员工数据    data:$("#empUpdateModal form").serialize()+"&_method=PUT"
    			$.ajax({
    				url:"${Path}/emp/"+$(this).attr("emp_edit_id"),
    				type:"PUT",
    				data:$("#empUpdateModal form").serialize(),
    				success: function(result) {
    					//alert(result.state);
    					//1,关闭对话框
    					$("#empUpdateModal").modal("hide");
    					//2,回到本页面
    					to_page(currentPage);
    				}
    			});
    		});
    		
    		$(document).on("click",".delete_btn",function() {
    			//1,弹出是否确认删除对话框   获取员工姓名
    			var empName = $(this).parents("tr").find("td:eq(2)").text();
    			//从删除按钮上获取id
    			var empId = $(this).attr("del-id");
    			if(confirm("确认删除[ " + empName + " ]吗?")) {
    				//确认删除.发送ajax请求删除即可
    				$.ajax({
    					url: "${Path}/emp/" + empId,
    					type: "DELETE",
    					success: function (result) {
    						//alert(result.str);
    						//回到本页
    						to_page(currentPage);
    					}
    				});
    			}
    		});
    		
    		
    		//完成全选/全不选
    		$("#check_all").click(function() {
    			//attr获取checked 是undefined
    			//我们这些dom原生的属性使用prop.attr获取自定义属性的值
    			//使用prop修改和读取原生的dom原生属性的值
    			//$(this).prop("checked");
    			$(".check_item").prop("checked",$(this).prop("checked"));
    		});
    		//给单个check_item 绑定点击事件
    		$(document).on("click",".check_item",function() {
    			//判断当前元素选中的元素是否5个
    			var flag = $(".check_item:checked").length == $(".check_item").length;
    			$("#check_all").prop("checked",flag);
    		});
    		
    		//点击全部删除按钮,将会批量删除
    		$("#emp_delete_all_btn").click(function() {
    			//遍历所有的,.check.item:checked
    			var empName = "";
    			var ids = "";
    			$.each($(".check_item:checked"),function() {
    				empName += $(this).parents("tr").find("td:eq(2)").text() + ",";
    				ids += $(this).parents("tr").find("td:eq(1)").text() + "-";
    			});
    			
    			//去除empNames多余的,号
    			empName = empName.substring(0,empName.length - 1);
    			//去除ids 多余的- 号
    			ids = ids.substring(0,ids.length - 1);
    			if(confirm("确认删除: " + empName + "?")) {
    				// 确认,发送ajax请求
    				$.ajax({
    					url:"${Path}/emp/"+ ids,
    					type:"DELETE",
    					success: function(result) {
    						alert(result.str);
    						//回到当前页面
    						to_page(currentPage);
    					}
    				});
    			}
    		});
    	</script>
    	
    	
  </body>
</html>

Msg类

package it.bean;

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

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude
public class Msg {

	// 状态码
	private Integer state;
	// 信息
	private String str;

	private Map<String, Object> ma = new HashMap<String, Object>();

	public Msg(Integer state, String str) {
		super();
		this.state = state;
		this.str = str;
	}

	public Msg(Integer state, String str, Map<String, Object> ma) {
		super();
		this.state = state;
		this.str = str;
		this.ma = ma;
	}

	public Msg() {
		super();
		// TODO Auto-generated constructor stub
	}

	public static Msg success() {
		Msg msg = new Msg();
		msg.setState(100);
		msg.setStr("成功");
		return msg;
	}

	public static Msg fail() {
		Msg msg = new Msg();
		msg.setState(200);
		msg.setStr("失败");
		return msg;
	}

	public Integer getState() {
		return state;
	}

	public Msg addAttribute(String str, Object object) {
		this.ma.put(str, object);
		return this;
	}

	public Map<String, Object> getMa() {
		return ma;
	}

	public void setMa(Map<String, Object> ma) {
		this.ma = ma;
	}

	public void setState(Integer state) {
		this.state = state;
	}

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

}

Department.java , Employee.java,…等都是 使用MyBatis逆向工程的.
所遇到的问题:(1)无法给客户端返回JSON.(2)日常手残,敲错id,变量名…
项目是跟着尚硅谷视频学的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值