使用ssm框架进行整合,实现一个小的项目,对员工信息的增删改查

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/mumihahaha/article/details/79014992
一、项目简介
项目基于Maven+SpringMVC+Spring+MyBatis+Bootstrap的组合,快速开发一个完整的CRUD功能,对员工数据进行增删查改。
项目效果图:

主页:
新增:

删除:

修改:

二、功能点
1、分页
2、数据校验(jquery前端校验+JSR303后端校验)
3、大量使用ajax技术,如在该项目中的用户名校验、编辑、单个删除、多个删除
4、Rest风格的URL;使用HTTP协议请求方式的动词,来表示对资源的操作(GET(查询),
     POST(新增),PUT(修改),DELETE(删除))
三、技术点
1、基础框架-ssm(SpringMVC+Spring+MyBatis)
2、数据库-MySQL
3、前端框架-bootstrap快速搭建简单美观的界面
4、项目的依赖管理-Maven
5、分页-pagehelper
6、逆向工程-MyBatis Generator



四、开发步骤:

1.创建一个maven web工程

2、使用pom.xml配置,引入项目依赖的jar包(Maven官网地址http://www.mvnrepository.com/)

·spring
·springmvc
·mybatis
·数据库连接池,驱动包
·其他(jstl,servlet-api,junit)等

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.linzhw</groupId>
  <artifactId>ssm-crud</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>ssm-crud Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <dependencies>
	
	<!-- 引入项目依赖的jar包 -->
	
	<!-- 引入pageHelper分页插件 -->
	<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
	<dependency>
	    <groupId>com.github.pagehelper</groupId>
	    <artifactId>pagehelper</artifactId>
	    <version>5.1.2</version>
	</dependency>
	
	
	<!-- MBG代码生成器  mybatis逆向工程生成对应的bean以及mapper -->
	<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
	<dependency>
	    <groupId>org.mybatis.generator</groupId>
	    <artifactId>mybatis-generator-core</artifactId>
	    <version>1.3.5</version>
	</dependency>
	
	
	<!-- springMVC、spring -->
	<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
  	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>4.3.7.RELEASE</version>
	</dependency>
	
	<!-- 返回json字符串的支持 -->
	<!-- 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数据校验支持 ;tomcat7及以上的服务器
		tomcat7以下的服务器:el表达式,额外给服务器的lib包中替换新的标准el
	-->
	<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
	<dependency>
	    <groupId>org.hibernate</groupId>
	    <artifactId>hibernate-validator</artifactId>
	    <version>5.4.1.Final</version>
	</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-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面向切面编程 -->
	<!-- 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>
	
	<!-- 数据库连接池 -->
	<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
	<dependency>
	    <groupId>c3p0</groupId>
	    <artifactId>c3p0</artifactId>
	    <version>0.9.1.2</version>
	</dependency>
	
	<!-- 驱动 -->
	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.41</version>
	</dependency>
	
	<!-- jstl -->
	<!-- https://mvnrepository.com/artifact/jstl/jstl -->
	<dependency>
	    <groupId>jstl</groupId>
	    <artifactId>jstl</artifactId>
	    <version>1.2</version>
	</dependency>
	
	<!-- servlet-api -->
	<!-- 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>
	
	<!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <!-- <scope>test</scope> -->
    </dependency>
    
    
  </dependencies>
  <build>
    <finalName>ssm-crud</finalName>
  </build>


</project>

3、引入bootstrap前端框架(下载地址:bootstraphttps://v3.bootcss.com/getting-started#download)

位置:src/main/webapp/static/

引入jquery-2.0.0.min.js(下载地址:http://jquery.com/download/)

位置:src/main/webapp/static/js/

4、编写ssm整合的关键配置文件

web

位置:src/main/webapp/WEB-INF/ web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0">
        
        <!-- 1、启动Spring容器 -->
		<context-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:applicationContext.xml</param-value>
		</context-param>
		<listener>
			<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
		</listener>      
        
        <!-- 2、springmvc的前端控制器 拦截所有请求-->
		<servlet>
			<servlet-name>dispatcherServlet</servlet-name>
			<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
			<load-on-startup>1</load-on-startup>
		</servlet> 
			
		<servlet-mapping>
			<servlet-name>dispatcherServlet</servlet-name>
			<url-pattern>/</url-pattern>
		</servlet-mapping>		
		
		<!-- 3、字符编码过滤器 一定要放在所有过滤器之前  -->
		<filter>
			<filter-name>CharacterEncodingFilter</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>forceRequestEncoding</param-name>
				<param-value>true</param-value>
			</init-param>
			<init-param>
				<param-name>forceResponseEncoding</param-name>
				<param-value>true</param-value>
			</init-param>
		</filter>
		<filter-mapping>
			<filter-name>CharacterEncodingFilter</filter-name>
			<url-pattern>/*</url-pattern>
		</filter-mapping>
	<!-- 使用Rest风格的URI 将页面普通的post请求转为指定的delete或者put请求 -->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<filter>
		<filter-name>HttpPutFormContentFilter</filter-name>
		<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HttpPutFormContentFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>


springmvc

位置:src/main/webapp/WEB-INF/ dispatcherServlet-servlet.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:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/context
           				http://www.springframework.org/schema/context/spring-context-3.0.xsd
           				http://www.springframework.org/schema/mvc
						http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
				
	<!-- SpringMVC的配置文件,包含网址跳转逻辑的控制,配置 -->
	<context:component-scan base-package="com.linzhw" 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/>
	<!-- 能支持springmvc更高级的一些功能,JSR303校验,快捷的ajax... -->
	<mvc:annotation-driven/>
</beans>

spring

位置:src/main/resources/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: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-3.0.xsd
				http://www.springframework.org/schema/context
   				http://www.springframework.org/schema/context/spring-context-3.0.xsd
   				http://www.springframework.org/schema/aop 
   				http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   				http://www.springframework.org/schema/tx 
   				http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<context:component-scan base-package="com.linzhw">
		<!-- spring扫描包:除了控制器其他都扫描 -->
		<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>
	
	<!-- =========================配置spring和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="com.linzhw.crud.dao"></property>
	</bean>
	
	<!-- 配置一个可以执行批量的sqlSession -->
	<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配置形式的事务(主要的都是使用配置式) -->
	<aop:config>
		<!-- 切入点表达式 -->
		<aop:pointcut expression="execution(* com.linzhw.crud.service..*(..))" id="txPoint"/>
		<!-- 配置事务增强 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
	</aop:config>
	
	<!-- 配置事务增强,事务如何切入 -->
	<!-- transaction-manager值默认是transactionManager -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
	
		<tx:attributes>
			<!-- 所有方法都是事务方法 -->
			<tx:method name="*"/>
			<!-- 以get开始的所有方法 -->
			<tx:method name="get*" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- spring配置文件的核心点(数据源,与mybatis的整合,事务控制) -->
</beans>

建数据库

部门表

员工表

外键


创建一个后缀为.properties文件,文件名为dbconfig.properties,必须有与spring配置中的一致

位置:src/main/resources/dbconfig.properties

mybatis

位置:src/main/resources/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"/>
 	</settings> 
	<typeAliases> 
  		<package name="com.linzhw.crud.bean"/>
 	</typeAliases>
	<plugins>
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
			<!-- 分页参数合理化 -->
			<property name="reasonable" value="true"/>
		</plugin>
	</plugins> 	
</configuration>


使用mybatis逆向工程生成对应的bean以及mapper

mbg.xml

<?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>
  <!-- 数据库驱动包位置 -->
  <!-- <classPathEntry location="E:\repository\mysql\mysql-connector-java\5.1.41\mysql-connector-java-5.1.41.jar" />  --> 
 
  <context id="DB2Tables" targetRuntime="MyBatis3">
  
  <!-- 生成的文件取消注释 设 value="true" -->
  <commentGenerator>  
            <property name="suppressAllComments" value="true" />  
  </commentGenerator>
  
  	<!-- 配置数据库连接 -->
    <jdbcConnection 
    	driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3366/ssm_crud"
        userId="root"
        password="123456">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>
	
	<!-- 指定javaBean生成的位置 -->
    <javaModelGenerator 
    	targetPackage="com.linzhw.crud.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="com.linzhw.crud.dao"  
    	targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

	<!-- table指定每个表的生成策略 -->
  	<table tableName="tbl_emp" domainObjectName="Emplovee"></table>
	<table tableName="tnl_dept" domainObjectName="Department"></table>
  </context>
</generatorConfiguration>

创建一个java类并运行,使用java代码和配置文件的方式来使用mybatis的逆向工程

http://www.mybatis.org/generator/running/running.html



位置:src/main/java/com/linzhw/crud/test/MBGTest.java

package com.linzhw.crud.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);
	}

}

根据需求修改mapper文件

src/main/java/com/linzhw/crud/dao/EmployeeMapper.java新增

List<Employee> selectByExampleWithDept(EmployeeExample example);

Employee selectByPrimaryKeyWithDept(Integer empId);

src/main/java/com/linzhw/crud/bean/Employee.java新增
    //希望查询员工信息的同时部门信息也是查询好的
    private Department department;
并添加get,set方法
	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

src/main/resources/mapper/EmployeeMapper.xml 新增

带部门查询

 <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>
<select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
      select
    <if test="distinct">
      distinct
    </if>
    <include refid="WithDept_Column_List" />
    FROM tbl_emp e
    left join tnl_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>  

按照主键来查询(在按部门查询也许添加以下这小段代码)

  <resultMap id="WithDeptResultMap" type="com.linzhw.crud.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" />
    <!-- 关联department信息 指定联合查询出的字段信息封装 -->
    <association property="department" javaType="com.linzhw.crud.bean.Department" >
    	<id column="dept_id" property="deptId" />
    	<result column="dept_name" property="deptName" />
    </association>
  </resultMap>
 
<!-- 查询员工同时带部门信息 -->
     <select id="selectByPrimaryKeyWithDept" parameterType="java.lang.Integer" resultMap="WithDeptResultMap">
      select 
    <include refid="WithDept_Column_List" />
     FROM tbl_emp e
    left join tnl_dept d on e.d_id=d.dept_id
     where emp_id = #{empId,jdbcType=INTEGER}
  </select>

5、测试mapper

package com.linzhw.crud.test;

import java.util.UUID;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.linzhw.crud.bean.Department;
import com.linzhw.crud.bean.Employee; 
import com.linzhw.crud.dao.DepartmentMapper;
import com.linzhw.crud.dao.EmployeeMapper;
 
/**
 * 测试dao层的工作
 * 推荐:Spring的项目就可以使用Spring的单元测试,可以自动注入我们需要的组件
 * 		1、导入SpringTest模块
 * 		2、@ContextConfiguration指定Spring配置文件的位置
 * 		3、直接autowired要使用的组件即可
 * @author linzhw
 * @creationTime 2017年12月19日下午8:04:40
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class MapperTest {
	
	@Autowired
	DepartmentMapper departmentMapper;
	
	@Autowired
	EmployeeMapper emploveeMapper;
	
	@Autowired
	SqlSession sqlSession;
	
	/**
	 * 测试DepartmentMapper
	 */
	@Test
	public void testCRUD(){
		/*//1、创建SpringIOC容器
		ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
		//2、从容器中获取mapper
		DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);*/
		
		System.out.println(departmentMapper);
		
		//1、插入几个部门
//		departmentMapper.insertSelective(new Department(null, "研发部"));
//		departmentMapper.insertSelective(new Department(null, "事业部"));
	
		//2、生成员工数据,测试员工插入
		//employeeMapper.insertSelective(new Employee(null, "session", "F", "session@163.com", 2));
		
		//System.out.println("插入成功");

		//3、批量插入多个员工;批量,使用可以执行批量操作的sqlSession

		/*for () {
			employeeMapper.insertSelective(new Employee(null, "Jerry1", "F", "Jerry1@163.com", 2));
			
		}*/
		EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
		for(int i=0;i<10;i++){
			String uid = UUID.randomUUID().toString().substring(0, 5)+i;
			mapper.insertSelective(new Employee(null, uid, "M", uid+"@github.com", 4));
		}
		System.out.println("批量新增完成");
	}
}

6、分页后台代码

service层

@Service
public class EmployeeService {

	@Autowired
	EmployeeMapper employeeMapper;
	
	/**
	 * 查询所有员工
	 * @return
	 */
	public List<Employee> getAll() {
		return employeeMapper.selectByExampleWithDept(null);
	}
}
引入分页插件(网址:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md)

在pom.xml中配置引入
在mybatis的全局配置文件配置分页插件

@Controller
public class EmployeeController {
	
	@Autowired
	EmployeeService employeeService;
@RequestMapping("/emps")						//默认显示第一页
	public String getEmps(@RequestParam(value="pn",defaultValue="1")Integer pn,Model model){
		//这不是一个分页查询
		//引入PageHelper分页插件
		//在查询之前只需要调用,传入页码,以及每页的大小
		PageHelper.startPage(pn, 5);
		//startPage后面紧跟的这个查询就是一个分页查询
		List<Employee> emps= employeeService.getAll();
		//使用pageInfo包装查询后的结果,只需要将pageInfo交给页面就行
		//封装详细的分页信息,包括有我们查询出来的数据,传入连续显示的页数
		PageInfo page = new PageInfo(emps,5);
		model.addAttribute("pageInfo",page);
		
		return "list";
	}
}

7、使用Spring单元测试测试分页请求

package com.linzhw.crud.test;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.github.pagehelper.PageInfo;
import com.linzhw.crud.bean.Employee;

/**
 * 使用Spring测试模块提供的测试请求功能,测试crud请求正确性
 * Spring4测试的时候,需要serclet3.0的支持
 * @author linzhw
 * @creationTime 2017年12月21日下午9:46:04
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"})
public class MvcTest {
	//传入Springmvc的ioc
	@Autowired
	WebApplicationContext context;
	//虚拟mvc请求,获取到处理结果
	MockMvc mockMvc;
	
	@Before
	public void initMockCMvc(){
		mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
	}

	@Test
	public void testPage() throws Exception{
		//模拟请求拿到返回值														  //显示第几页
		MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "2")).andReturn();
		
		//请求成功以后,请求域中会有pageInfo,我们可以取出pageInfo进行验证
		MockHttpServletRequest request = result.getRequest();
		PageInfo pi = (PageInfo) request.getAttribute("pageInfo");
		System.out.println("当前页码:"+pi.getPageNum());
		System.out.println("总页码:"+pi.getPages());
		System.out.println("总记录数:"+pi.getTotal());
		System.out.println("在页面需要连续显示的页码");
		int[] nums = pi.getNavigatepageNums();
		for (int i : nums) {
			System.out.println(" "+i);
		}
		
		//获取员工数据
		List<Employee> list = pi.getList();
		for (Employee employee : list) {
			System.out.println("ID: "+employee.getEmpId()+"===Name: "+employee.getEmpName());
		}
	}
}

前端页面

首页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<jsp:forward page="/emps"></jsp:forward>
<!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>Insert title here</title>

<script type="text/javascript" src="static/js/jquery1.32.min.js"></script>

<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
	<button type="button" class="btn btn-success">按钮</button> 
</body>
</html>

list页面

<%@ 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路径:
			不以/开始的相对路径,找资源,以当前资源的路径为基准,经常容易出现问题
			以/开始的相对路径,找资源,以服务器的路径为标准(http://localhost:3366);需要加上项目名
				http://localhost:3366/crud
 -->
<script type="text/javascript" src="${APP_PATH}/static/js/jquery1.32.min.js"></script>
<link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
	<!-- 搭建显示页面 -->
	<div class="container">
		<!-- 标题 -->
		<div class="row">
			<div class="col-md-12">
			<h1>SSM-CRUD</h1>
		</div>
		</div>
		<!-- 按钮 -->
		<div class="row">
			 <div class="col-md-4 col-md-offset-8">
			 	<button class="btn btn-primary">新增</button>
			 	<button class="btn btn-danger">删除</button>
			 </div>
		</div>
		<!-- 显示表格数据 -->
		<div class="row">
			<div class="col-md-12">
				<table class="table table-hover">
					<tr>
						<th>#</th>
						<th>empName</th>
						<th>gender</th>
						<th>email</th>
						<th>deptName</th>
						<th>操作</th>
					</tr>
					<c:forEach items="${pageInfo.list}" var="emp">
						<tr>
							<th>${emp.empId}</th>
							<th>${emp.empName}</th>
							<th>${emp.gender=="M"?"男":"女"}</th>
							<th>${emp.email}</th>
							<th>${emp.department.deptName}</th>
							<th>
								<button class="btn-primary btn-sm">
									<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 
									编辑
								</button>
								<button class="btn-danger btn-sm">
									<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> 
									删除
								</button>
							</th>
						</tr>
					</c:forEach>
				</table>
		</div>
		<!-- 显示分页信息 -->
		<div class="row">
			<!-- 分页文字信息 -->
			<div class="col-md-6">
				当前${pageInfo.pageNum}页,总${pageInfo.pages}页,总${pageInfo.total }条记录
			</div>
		<!-- 分页条信息 -->
		<div class="col-md-6">
				<nav aria-label="Page navigation">
				  <ul class="pagination">
				  <li><a href="${APP_PATH }/emps?pn=1">首页</a></li>
				  <c:if test="${pageInfo.hasPreviousPage}">
				    <li>
				      <a href="${APP_PATH }/emps?pn=${pageInfo.pageNum-1}" aria-label="Previous">
				        <span aria-hidden="true">«</span>
				      </a>
				    </li>
				  </c:if>
				    <c:forEach items="${pageInfo.navigatepageNums}" var="page_Num">
				   		 <c:if test="${page_Num == pageInfo.pageNum }">
				   			<li class="active"><a href="#">${page_Num}</a></li>
				   		 </c:if>
				   		 <c:if test="${page_Num != pageInfo.pageNum }">
				   		 	<li><a href="${APP_PATH }/emps?pn=${page_Num}">${page_Num}</a></li>
				   		 </c:if>
				    </c:forEach>
				    <c:if test="${pageInfo.hasNextPage}">
				    <li>
				      <a href="${APP_PATH }/emps?pn=${pageInfo.pageNum+1}" aria-label="Next">
				        <span aria-hidden="true">»</span>
				      </a>
				    </li>
				    </c:if>
				    	<li><a href="${APP_PATH }/emps?pn=${pageInfo.pages}">末页</a></li>
				  </ul> 
				</nav>
			</div>
		</div>
		<div class="row"></div>
	</div>
</body>
</html>

上面这种方式是从首页转到/emps请求,控制器收到处理分页数据和分页信息,由控制器将处理后的信息转到list页面<c:forEach></c:forEach>  、EL表达式  遍历展示出的数据

这种做法只适用于浏览器和服务器的交互,在现在的移动互联网时代,我们的客户端发送请求不仅仅是浏览器,它可能是Android客户端,或是iOS客户端,服务器如果再转发页面给移动端进行解析,就会很费劲,现在最常用的解决方法是服务器以Json形式返回给这些客户端

下面使用纯Ajax实现增删改查,实现系统的可扩张性和平台的无关性


URl:
/emp/{id} GET查询员工
/emp      POST保存员工
/emp/{id} PUT修改员工
/emp/{id} DELETE 删除员工

查询-ajax
1、index.jsp页面直接发送ajax请求进行员工分页数据的查询
2、服务器将查出的数据,以json字符串的形式返回给浏览器
3、浏览器收到js字符串。可以使用js对json进行解析,使用通过dom增删改改变页面。
4、返回json。实现客户端的无关性。

新增-逻辑
1、在index.jsp页面点击"新增"
2、弹出新增对话框
3、去数据库查询部门列表,显示在对话框中
4、用户输入数据,并进行校验
·jquery前端校验,ajax用户名重复校验,重要数据(后端校验(JSR303),唯一约束);
5、完成保存

修改-逻辑
1、点击编辑
2、弹出用户修改的模态框(显示用户信息)
3、点击更新,完成用户修改

删除-逻辑
1、单个删除
·URl:/emp{id} DELETE

2、多个删除


首页

<%@ 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路径:
			不以/开始的相对路径,找资源,以当前资源的路径为基准,经常容易出现问题
			以/开始的相对路径,找资源,以服务器的路径为标准(http://localhost:3366);需要加上项目名
				http://localhost:3366/crud
 -->
<script type="text/javascript" src="${APP_PATH}/static/js/jquery-2.0.0.min.js"></script>
<link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="${APP_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">×</span></button>
        <h4 class="modal-title">员工修改</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="empName_update_static"></p>
		      <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_update_input" placeholder="email@163.com">
		      <span class="help-block"></span>
		    </div>
		  </div>
		  <div class="form-group">
		   <label class="col-sm-2 control-label">gender</label>
		    <label class="radio-inline">
			  <input type="radio" name="gender" id="gender1_update_input" value="M" checked="checked"> 男
			</label>
			<label class="radio-inline">
			  <input type="radio" name="gender" id="gender2_update_input" value="F"> 女
			</label>
		  </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="dId"></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">×</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="email" class="form-control" id="email_add_input" placeholder="email@163.com">
		      <span class="help-block"></span>
		    </div>
		  </div>
		  <div class="form-group">
		   <label class="col-sm-2 control-label">gender</label>
		    <label class="radio-inline">
			  <input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"> 男
			</label>
			<label class="radio-inline">
			  <input type="radio" name="gender" id="gender2_add_input" value="F"> 女
			</label>
		  </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="dId"></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>
		</div>
		<!-- 按钮 -->
		<div class="row">
			 <div class="col-md-4 col-md-offset-8">
			 	<button class="btn btn-primary" id="emp_add_modal_btn">新增</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>empName</th>
							<th>gender</th>
							<th>email</th>
							<th>deptName</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,currentPage;
		//1、页面加载完成后,直接去发送一个ajax请求,要到分页数据
		$(function(){
			//去首页
			to_page(1);
		});
		
		function to_page(pn){
			$.ajax({
				url:"${APP_PATH}/emps",
				data:"pn="+pn,
				type:"GET",
				success:function(result){
					//console.log(result);
					//1、解析并显示员工数据
					build_emps_table(result);
					//2、解析并显示分页信息
					buid_page_info(result);
					//3、解析显示分页条
					build_page_nav(result);
				}
			});
		}
		
		function build_emps_table(result){
			//先清空table表格,否则上之前所访问的数据还在
			$("#emps_table tbody").empty();
			//将一个 JSON 字符串转换为对象  引入jquery2.0以上的并不需要这样做
			//var emps = JSON.parse(result);
			var emps = result.extend.pageInfo.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.gender=='M'?"男":"女");
				var emailTd = $("<td></td>").append(item.email);
				var deptNameTd = $("<td></td>").append(item.department.deptName);
				var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
								.append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");
				//为编辑按钮添加一个自定义属性,表示当前员工id
				editBtn.attr("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 = $("<td></td>").append(editBtn).append(" ").append(delBtn);
				//append方法执行完成以后还是返回原来的元素
				$("<tr></tr>").append(checkBoxTd)
					.append(empIdTd)
					.append(empNameTd)
					.append(genderTd)
					.append(emailTd)
					.append(deptNameTd)
					.append(btnTd)
					.appendTo("#emps_table tbody");
			});
		}
		
		//解析分页信息
		function buid_page_info(result){
			$("#page_info_area").empty();
			/* var pageInfo = JSON.parse(result);
			var pageInfo2 = pageInfo.extend.pageInfo; */
			$("#page_info_area").append("当前"+result.extend.pageInfo.pageNum+"页,总"+result.extend.pageInfo.pages+"页,总"+result.extend.pageInfo.total+"条记录");
			totalREcord = result.extend.pageInfo.total;
			currentPage = result.extend.pageInfo.pageNum;
		}
		
		//解析显示分页条,点击分页条要能去下一页...
		function build_page_nav(result){
			$("#page_nav_area").empty();
			/* var pageNav = JSON.parse(result);
			var pageNav2 = pageNav.extend.pageInfo; */
			var ul =$("<ul></ul>").addClass("pagination");
			//构建元素
			var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
			var prePageLi = $("<li></li>").append($("<a></a>").append("«"));
			if(result.extend.pageInfo.hasPreviousPage == false){
				firstPageLi.addClass("disabled");
				prePageLi.addClass("disabled");
			}else{
				//为元素添加翻页的事件
				firstPageLi.click(function(){
					to_page(1);
				});
				prePageLi.click(function(){
					to_page(result.extend.pageInfo.pageNum-1);
				});
				
			}
			var nextPageLi = $("<li></li>").append($("<a></a>").append("»"));
			var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
			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);
				});
			}
			//添加首页和前一页的提示
			ul.append(firstPageLi).append(prePageLi);
			//遍历页码号1,2,3.遍历给ul中添加页码提示
			$.each(result.extend.pageInfo.navigatepageNums,function(index,item){
				var numLi = $("<li></li>").append($("<a></a>").append(item));
				if(result.extend.pageInfo.pageNum == item){
					numLi.addClass("active");
				}
				numLi.click(function(){
					to_page(item);					
				});
				ul.append(numLi);
			});
			//添加下一页和末页的提示
			ul.append(nextPageLi).append(lastPageLi);
			
			//把ul加入到nav
			var navEle = $("<nav></nav>").append(ul);
			navEle.appendTo("#page_nav_area");
		}
		
		//清空表单样式及内容
		function reset_form(ele){
			$(ele)[0].reset();
			//清空表单样式
			$(ele).find("*").removeClass("has-success has-error");
			$(ele).find(".help-block").text("");
		}
		
		
		//点击新增按钮弹出模态框
		$("#emp_add_modal_btn").click(function(){
			//发送ajax请求,查出部门信息,显示下拉列表中
			//清除表单,(表单完整重置(表单的数据,表单的样式))
			reset_form("#empAddModal form");
			$("#empAddModal form")[0].reset();
			getDepts("#empAddModal select");
			//弹出模态框
			$("#empAddModal").modal({
				backdrop:"static"
			});
		});
		
		//查出所有的部门信息并显示在下拉列表中
		function getDepts(ele){
			//清空之前下拉列表的值
			$(ele).empty();
			$.ajax({
				url:"${APP_PATH}/depts",
				type:"GET",
				success:function(result){
					//console.log(result);
					//显示部门信息在下拉列表中
					//$("#empAddModal select").append("")
					//{code: 100, msg: "处理成功!", extend: {…}}
					//alert(result);
					$.each(result.extend.depts,function(){
						var optionEle = $("<option></option>").append(this.deptName).attr("value",this.deptId);
						optionEle.appendTo(ele);
					});
				}
			});
		}
		
		//校验表单数据
		function varlidate_add_form(){
			//1、拿到要检验的数据,使用正则表达式
			//验证用户名
			var empName = $("#empName_add_input").val();
			var regName = /^([a-zA-Z0-9_-]{6,16})|(^[\u2E80-\u9FFF]{2,5})$/;
			//alert(regName.test(empName));
			if(!regName.test(empName)){
				//alert("用户名可以是2~5位中文或者6~16位英文和数字的组合");
				show_validate_msg("#empName_add_input","error","用户名可以是2~5位中文或者6~16位英文和数字的组合");
				return false;
			}else{
				show_validate_msg("#empName_add_input","success","");
			}
			//验证email
			var email = $("#email_add_input").val();
			var regEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/;
			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){
			//清除当前元素的校验状态
			$(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);
			}
		}
		
		$("#empName_add_input").change(function(){
			//发送ajax请求校验用户名是否可用
			var empName = this.value;
			$.ajax({
				url:"${APP_PATH}/checkuser",
				data:"empName="+empName,
				type:"POST",
				success:function(result){
					if(result.code==100){
						show_validate_msg("#empName_add_input","success","用户名可用");
						$("#emp_save_btn").attr("ajax-va","success");
					}else{
						show_validate_msg("#empName_add_input","error",result.extend.va_msg);
						$("#emp_save_btn").attr("ajax-va","error");
					}
				}
			});
		});
		
		//点击保存,保存员工
		$("#emp_save_btn").click(function(){
			//1、模态框中填写的表单数据提交给服务器进行保存
			//2、先对要提交给服务器的数据进行校验
			if(!varlidate_add_form()){
				return false;
			};
			//3、判断之前的ajax用户名校验是否成功,如果成功才保存
			if($(this).attr("ajax-va")=="error"){
				return false;
			}
			//4、发送ajax请求保存员工
			$.ajax({
				url:"${APP_PATH}/emp",
				type:"POST",
				data:$("#empAddModal form").serialize(),
				success:function(result){
					//alert(result.msg);
					if(result.code == 100){
						//员工保存成功
						//1、关闭模态框
						$("#empAddModal").modal('hide')
						//2、来到最后一页,显示刚才保存的数据
						//发送ajax请求显示最后一页数据即可
						to_page(totalREcord);
					}else{
						//显示失败信息
						//console.log(result);
						//有哪个字段错误的信息就显示哪个字段的信息
						if(undefined != result.extend.errorFields.email){
							//显示邮箱错误信息
							show_validate_msg("#email_add_input","error",result.extend.errorFields.email);
						}
						if(undefined != result.extend.errorFields.empName){
							//显示用户名错误信息
							show_validate_msg("#empName_add_input","error",result.extend.errorFields.empName);
						}
						alert(result.extend.errorFields.email);
						alert(result.extend.errorFields.empName);
							
						}
					}
			});
		});
		
		//1、我们是按钮创建之前就绑定了click,所以绑定不上
		//1)、可以创建按钮的时候绑定。     2)、绑定点击live()
		//jquery新版本没有live,使用out进行替代
		$(document).on("click",".edit_btn",function(){
			//alert("edit");
			//1、查出部门信息,并显示部门列表
			getDepts("#empUpdateModal select");
			//2、查出员工信息,显示员工信息
			getEmp($(this).attr("edit-id"));
			
			//3、把员工的id传递给模态框的更新按钮
			$("#emp_update_btn").attr("edit-id",$(this).attr("edit-id"));
			$("#empUpdateModal").modal({
				backdrop:"static"
			});
		});
		
		function getEmp(id){
			$.ajax({
				url:"${APP_PATH}/emp/"+id,
				type:"GET",
				success:function(result){
					//console.log(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]);
				}
			});
		}
		
		//点击更新,更新员工信息
		$("#emp_update_btn").click(function(){
			//1、验证邮箱是否合法
			var email = $("#email_update_input").val();
				var regEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/;
				if(!regEmail.test(email)){
					show_validate_msg("#email_update_input","error","邮箱格式不正确");
					return false;
				}else{
					show_validate_msg("#email_update_input","success","");
				}
			//2、发送ajax请求保存更新员工数据
			$.ajax({
				url:"${APP_PATH}/emp/"+$(this).attr("edit-id"),
				type:"PUT",
				data:$("#empUpdateModal form").serialize(),
				success:function(result){
					//alert(result.msg);
					//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();
			var emdId = $(this).attr("del-id");
			//alert($(this).parents("tr").find("td:eq(1)").text());
			if(confirm("确认删除【"+empName+"】吗?")){
				//确认,发送ajax请求删除即可
				$.ajax({
					url:"${APP_PATH}/emp/"+emdId,
					type:"DELETE",
					success:function(result){
						alert(result.msg);
						//回到本页
						to_page(currentPage);
					}
				})
			}
		});
		
		//完成全选/全不选功能
		$("#check_all").click(function(){
			//attr获取checked是undefined;
			//我们这些dom原生的属性;attr获取自定义的属性
			//prop修改和读取dom原生属性的值
			//alert($(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(){
			var empNames = "";
			var del_idstr = "";
			$.each($(".check_item:checked"),function(){
				//this
				empNames += $(this).parents("tr").find("td:eq(2)").text()+",";
				//组装员工id字符串
				del_idstr += $(this).parents("tr").find("td:eq(1)").text()+"-";
			});
			//去除empNames多余的,
			empNames = empNames.substring(0,empNames.length-1);
			//去除删除id多余的-
			del_idstr = del_idstr.substring(0,del_idstr.length-1);
			if(confirm("确认删除【"+empNames+"】吗?")){
				//发送ajax请求删除
				$.ajax({
					url:"${APP_PATH}/emp/"+del_idstr,
					type:"DELETE",
					success:function(result){
						alert(result.msg);
						//回到当前页面
						to_page(currentPage);
					}
				});
			}
		});
	</script>
</body>
</html>
控制器

package com.linzhw.crud.controller;

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

import javax.servlet.http.HttpServletRequest;
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.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.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linzhw.crud.bean.Employee;
import com.linzhw.crud.bean.Msg;
import com.linzhw.crud.service.EmployeeService;

/**
 * 处理CRUD请求
 * @author linzhw
 * @creationTime 2017年12月21日下午5:10:17
 */
@Controller
public class EmployeeController {
	
	@Autowired
	EmployeeService employeeService;
	
	/**
	 * 单个批量二合一
	 * 批量删除:1-2-3
	 * 单个删除:1
	 * @param id
	 * @return
	 */
	
	@ResponseBody
	@RequestMapping(value="/emp/{ids}",method=RequestMethod.DELETE)
	public Msg deleteEmp(@PathVariable("ids")String ids){
		//批量删除
		if (ids.contains("-")) {
			List<Integer> del_ids = new ArrayList<>();
			String[] str_ids = ids.split("-");
			//封装id的集合
			for (String string : str_ids) {
				del_ids.add(Integer.parseInt(string));
			}
			employeeService.deleteBath(del_ids);
			//单个删除
		}else {
			Integer id = Integer.parseInt(ids);
			employeeService.deleteEmp(id);
		}
		return Msg.success();
	}
	
	/**
	 * 如果直接发送ajax=PUT形式的请求
	 * 封装数据
	 * Employee 
	 * [empId=3555,empName=null,gender=null email=null, dId= null]
	 * 
	 * 
	 * 问题:
	 * 请求体中有数据
	 * 但是Employee对象封装不上
	 * update tbl_emp  where emp_id = 3555
	 * 
	 * 原因:
	 * Tomcat:
	 * 		1、将请求中的数据,封装一个map
	 * 		2、request.getParameter("empName")就会从这个map中取值
	 * 		3、SpringMVC封装POJO对象的时候
	 * 			会把POJO中每个属性的值,request.getParamer("email");
	 *	AJAX发送PUT请求引发的血案:
	 *			PUT请求,请求体中的数据,request。getParameter("empName")拿不到
	 *			Tomcat一看是PUT请求不会封装请求体中的数据为map,只有POST形式的请求才会封装请求体为map
	 * 
	 * 解决方法:
	 * 我们要能直接发送PUT之类的请求还要封装请求体中的数据
	 * 配置上HttpPutFormContentFilter
	 * 他的作用:将请求体中的数据解析包装成一个map,
	 * request被重新包装,request.getParameter()被重写,就会从自己封装的map中取出数据
	 * 员工更新方法
	 * @param employee
	 * @return
	 */
	
	@ResponseBody
	@RequestMapping(value="/emp/{empId}",method=RequestMethod.PUT)
	public Msg saveEmp(Employee employee,HttpServletRequest request){
		System.out.println("请求体中的值: "+request.getParameter("gender"));
		System.out.println("将要更新的员工数据:"+employee);
		employeeService.updateEmp(employee);
		return Msg.success();
	}
	
	/**
	 * 根据id查询员工
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
	@ResponseBody
	public Msg getEmp(@PathVariable("id")Integer id){
		
		Employee employee = employeeService.getEmp(id);
		return Msg.success().add("emp", employee);
		
	}
	
	/**
	 * 检查用户名是否可用
	 * @param empName
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/checkuser")
	public Msg checkuser(@RequestParam("empName")String empName){
		//先判断用户名是否是合法的表达式;
		String regx ="(^([a-zA-Z0-9_-]{6,16})|(^[\u2E80-\u9FFF]{2,5})$)";
		if(!empName.matches(regx)){
			return Msg.fail().add("va_msg", "用户名必须是6~16位数字和字母的组合或者2~5位中文");
		}
		
		//数据库用户名重复校验
		boolean b = employeeService.checkUser(empName);
		if(b){
			return Msg.success();
		}else{
			return Msg.fail().add("va_msg", "用户名不可用");
		}
	}
	
	/**
	 * 员工保存
	 * 1、支持JSR303校验
	 * 2、导入Hibernate-Validator
	 * @return
	 */
	@RequestMapping(value="/emp",method=RequestMethod.POST)
	@ResponseBody
	public Msg saveEmp(@Valid Employee employee,BindingResult result){
		if(result.hasErrors()){
			//校验失败,应该返回失败,在模态框中显示检验失败错误的信息
			Map<String, Object> map = new HashMap<>();
			List<FieldError> errors = result.getFieldErrors();
			for (FieldError fieldError : errors) {
				System.out.println("错误的字段名: "+fieldError.getField());
				System.out.println("错误信息:"+fieldError.getDefaultMessage());
				map.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			return Msg.fail().add("errorFields", map);
		}else {
			employeeService.saveEmp(employee);
			return Msg.success();
		}
		
	}
	
	/**
	 * 导入jackson包,
	 * @param pn
	 * @return
	 */
	@RequestMapping("/emps")
	@ResponseBody
	public Msg getEmpsWithJson(@RequestParam(value="pn",defaultValue="1")Integer pn){
		//这不是一个分页查询
		//引入PageHelper分页插件
		//在查询之前只需要调用,传入页码,以及每页的大小
		PageHelper.startPage(pn, 5);
		//startPage后面紧跟的这个查询就是一个分页查询
		List<Employee> emps= employeeService.getAll();
		//使用pageInfo包装查询后的结果,只需要将pageInfo交给页面就行
		//封装详细的分页信息,包括有我们查询出来的数据,传入连续显示的页数
		PageInfo page = new PageInfo(emps,5);
		return Msg.success().add("pageInfo",page);
	}
	/**
	 * 查询员工数据(分页查询)
	 * @return
	 */
	//@RequestMapping("/emps")						//默认显示第一页
	public String getEmps(@RequestParam(value="pn",defaultValue="1")Integer pn,Model model){
		//这不是一个分页查询
		//引入PageHelper分页插件
		//在查询之前只需要调用,传入页码,以及每页的大小
		PageHelper.startPage(pn, 5);
		//startPage后面紧跟的这个查询就是一个分页查询
		List<Employee> emps= employeeService.getAll();
		//使用pageInfo包装查询后的结果,只需要将pageInfo交给页面就行
		//封装详细的分页信息,包括有我们查询出来的数据,传入连续显示的页数
		PageInfo page = new PageInfo(emps,5);
		model.addAttribute("pageInfo",page);
		
		return "list";
	}
}

后端校验(JSR303)

 @Pattern(regexp="^([a-zA-Z0-9_-]{6,16})|(^[\\u2E80-\\u9FFF]{2,5})$"
    		,message="用户名必须是2~5位中文或者6~16位英文和数字的组合")
    private String empName;

    private String gender;

    //@Email
    @Pattern(regexp="^[a-z\\d]+(\\.[a-z\\d]+)*@([\\da-z](-[\\da-z])?)+(\\.{1,2}[a-z]+)+$"
    		,message="邮箱格式不正确")
    private String email;

本项目为本人根据腾讯课堂尚硅谷学院ssm-crud编写的项目


展开阅读全文

没有更多推荐了,返回首页