SSM整合-实现CRUD操作
一、技术点
1.框架:SSM-Spring,SpringMVC,MyBatis
2.数据库:Mysql
3.前端展示: BootStrap ,JSP,Ajax
4.版本管理: maven
5.其他:分页插件-pageHelper ,逆向工程-MyBatis Generator
二、环境搭建
2.1新建项目,添加依赖
<!-- 分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
<!-- MyBatis逆向工程-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!-- SpringMVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- JSON-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
<!-- JDBC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Spring测试单元-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- spring AOP-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- mybatis整合Spring的适配包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- 阿里Durid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.5</version>
</dependency>
<!-- mysql连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 测试单元-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
2.2BootStrap框架
<!-- Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
2.3SSM整合相关配置文件
- web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 1.Spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- 4.配置SpringMVC的乱码过滤-->
<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>
<!--5. 使用Rest风格URI,将页面普通的POST请求转换为指定的Delete或者put请求-->
<filter>
<filter-name>httpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>httpPutFormContentFilter</filter-name>
<servlet-name>dispatcherServlet</servlet-name>
</filter-mapping>
<!-- 2.监听器:在Servlet初始化之前加载ApplicationContext,把spring容器注入-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 3.SpringMVC 前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- spring配置
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--1.开启注解扫描-->
<context:component-scan base-package="com.wdzl">
<!--不扫描Controller-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--2.引入外部配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--.配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--配置连接池初始化大小-->
<property name="initialSize" value="3"/>
<!--最小空闲池-->
<property name="minIdle" value="20"/>
<!--定义最大连接数-->
<property name="maxActive" value="30"/>
<!--配置获取连接等待超时的时间,单位时毫秒-->
<property name="maxWait" value="60000"/>
<!--配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位时毫秒-->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!--配置一个连接池在池中最小生存时间,单位时毫秒-->
<property name="minEvictableIdleTimeMillis" value="300000"/>
</bean>
<!--SqlSessionFactory(MyBatis核心配置)-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--数据源-->
<property name="dataSource" ref="dataSource"/>
<!-- 别名-->
<property name="typeAliasesPackage" value="com.wdzl.bean"/>
<!--关联Mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--5.配置扫描器MapperScannerConfigure,需要mybatis-spring.jar-->
<bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--Dao层接口所在的包名,Spring自动去查找包下的接口-->
<property name="basePackage" value="com.wdzl.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!--配置事务管理器-->
<bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" autowire="byName"></bean>
<!--配置事务如何增强-->
<tx:advice id="txAdvice" transaction-manager="transactionManger">
<tx:attributes>
<!--所有方法都是事务-->
<tx:method name="*"/>
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 切入点-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.wdzl.service..*(..))"/>
<!-- 切入点与增强关联-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
</aop:config>
</beans>
- springMVC配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.wdzl" use-default-filters="false">
<!--只扫描@Controller-->
<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 name="suffix" value=".jsp" />
</bean>
<!--常用的两个配置-->
<!--静态资源访问:将不能处理的请求交给Tomcat处理-->
<mvc:default-servlet-handler/>
<!--注解驱动:可以使用mvc高级功能:Ajax,Json,校验-->
<mvc:annotation-driven/>
</beans>
- mybatis配置
<?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="cacheEnabled" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 起别名-->
<typeAliases>
<package name="com.wdzl.bean"/>
</typeAliases>
<!-- 分页插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
</configuration>
外部配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm_crud?useUnicode=true&characterEncoding=utf8&serverTimeZone=UTC&useSSL=false
jdbc.username=root
jdbc.password=13992794421
2.4 源代码编写
1.数据库建库建表
2.使用逆向工程生成实体类,Dao层接口,mapper
Department
public class Department {
private Integer deptId;
private String deptName;
@Override
public String toString() {
return "Department{" +
"deptId=" + deptId +
", deptName='" + deptName + '\'' +
'}';
}
public Department() {
}
public Department(Integer deptId, String deptName) {
this.deptId = deptId;
this.deptName = deptName;
}
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName == null ? null : deptName.trim();
}
}
2.Employee
public class Employee {
private Integer empId;
@Override
public String toString() {
return "Employee{" +
"empId=" + empId +
", empName='" + empName + '\'' +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
", deptId=" + deptId +
", department=" + department +
'}';
}
@Pattern(regexp = "^[a-z0-9_-]{3,16}",message = "用户名格式错误")
private String empName;
private String gender;
@Email
private String email;
private Integer deptId;
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Employee() {
}
public Employee(Integer empId, String empName, String gender, String email, Integer deptId) {
this.empId = empId;
this.empName = empName;
this.gender = gender;
this.email = email;
this.deptId = deptId;
}
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName == null ? null : empName.trim();
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender == null ? null : gender.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
}
DepartmentMapper接口
public interface DepartmentMapper {
long countByExample(DepartmentExample example);
int deleteByExample(DepartmentExample example);
int deleteByPrimaryKey(Integer deptId);
int insert(Department record);
int insertSelective(Department record);
List<Department> selectByExample(DepartmentExample example);
Department selectByPrimaryKey(Integer deptId);
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接口
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> selectByExampleWithDept(EmployeeExample example);
Employee selectByPrimaryKeyWithDept(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);
}
DepartmentMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wdzl.dao.DepartmentMapper">
<resultMap id="BaseResultMap" type="com.wdzl.bean.Department">
<id column="dept_id" jdbcType="INTEGER" property="deptId" />
<result column="dept_name" jdbcType="VARCHAR" property="deptName" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
dept_id, dept_name
</sql>
<select id="selectByExample" parameterType="com.wdzl.bean.DepartmentExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from dept
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from dept
where dept_id = #{deptId,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from dept
where dept_id = #{deptId,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.wdzl.bean.DepartmentExample">
delete from dept
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.wdzl.bean.Department">
insert into dept (dept_id, dept_name)
values (#{deptId,jdbcType=INTEGER}, #{deptName,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.wdzl.bean.Department">
insert into dept
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="deptId != null">
dept_id,
</if>
<if test="deptName != null">
dept_name,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="deptId != null">
#{deptId,jdbcType=INTEGER},
</if>
<if test="deptName != null">
#{deptName,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.wdzl.bean.DepartmentExample" resultType="java.lang.Long">
select count(*) from dept
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update dept
<set>
<if test="record.deptId != null">
dept_id = #{record.deptId,jdbcType=INTEGER},
</if>
<if test="record.deptName != null">
dept_name = #{record.deptName,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update dept
set dept_id = #{record.deptId,jdbcType=INTEGER},
dept_name = #{record.deptName,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.wdzl.bean.Department">
update dept
<set>
<if test="deptName != null">
dept_name = #{deptName,jdbcType=VARCHAR},
</if>
</set>
where dept_id = #{deptId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.wdzl.bean.Department">
update dept
set dept_name = #{deptName,jdbcType=VARCHAR}
where dept_id = #{deptId,jdbcType=INTEGER}
</update>
</mapper>
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wdzl.dao.EmployeeMapper">
<resultMap id="BaseResultMap" type="com.wdzl.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="dept_id" jdbcType="INTEGER" property="deptId" />
</resultMap>
<resultMap id="WithDeptResultMap" type="com.wdzl.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" />
<association property="department" javaType="com.wdzl.bean.Department">
<id column="dept_id" property="deptId"></id>
<result column="dept_name" property="deptName"/>
</association>
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
emp_id, emp_name, gender, email, dept_id
</sql>
<sql id="WithDept_Column_List">
e.emp_id, e.emp_name, e.gender, e.email, d.dept_id,d.dept_name
</sql>
<select id="selectByExample" parameterType="com.wdzl.bean.EmployeeExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from emp
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from emp
where emp_id = #{empId,jdbcType=INTEGER}
</select>
<select id="selectByExampleWithDept" parameterType="com.wdzl.bean.EmployeeExample" resultMap="WithDeptResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="WithDept_Column_List" />
from emp e
left join dept d on e.dept_id = d.dept_id
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKeyWithDept" parameterType="java.lang.Integer" resultMap="WithDeptResultMap">
select
<include refid="WithDept_Column_List" />
from emp e
left join dept d on e.dept_id = d.dept_id
where emp_id = #{empId,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from emp
where emp_id = #{empId,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.wdzl.bean.EmployeeExample">
delete from emp
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.wdzl.bean.Employee">
insert into emp (emp_id, emp_name, gender,
email, dept_id)
values (#{empId,jdbcType=INTEGER}, #{empName,jdbcType=VARCHAR}, #{gender,jdbcType=CHAR},
#{email,jdbcType=VARCHAR}, #{deptId,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.wdzl.bean.Employee">
insert into emp
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="empId != null">
emp_id,
</if>
<if test="empName != null">
emp_name,
</if>
<if test="gender != null">
gender,
</if>
<if test="email != null">
email,
</if>
<if test="deptId != null">
dept_id,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="empId != null">
#{empId,jdbcType=INTEGER},
</if>
<if test="empName != null">
#{empName,jdbcType=VARCHAR},
</if>
<if test="gender != null">
#{gender,jdbcType=CHAR},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="deptId != null">
#{deptId,jdbcType=INTEGER},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.wdzl.bean.EmployeeExample" resultType="java.lang.Long">
select count(*) from emp
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update emp
<set>
<if test="record.empId != null">
emp_id = #{record.empId,jdbcType=INTEGER},
</if>
<if test="record.empName != null">
emp_name = #{record.empName,jdbcType=VARCHAR},
</if>
<if test="record.gender != null">
gender = #{record.gender,jdbcType=CHAR},
</if>
<if test="record.email != null">
email = #{record.email,jdbcType=VARCHAR},
</if>
<if test="record.deptId != null">
dept_id = #{record.deptId,jdbcType=INTEGER},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update emp
set emp_id = #{record.empId,jdbcType=INTEGER},
emp_name = #{record.empName,jdbcType=VARCHAR},
gender = #{record.gender,jdbcType=CHAR},
email = #{record.email,jdbcType=VARCHAR},
dept_id = #{record.deptId,jdbcType=INTEGER}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.wdzl.bean.Employee">
update emp
<set>
<if test="empName != null">
emp_name = #{empName,jdbcType=VARCHAR},
</if>
<if test="gender != null">
gender = #{gender,jdbcType=CHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="deptId != null">
dept_id = #{deptId,jdbcType=INTEGER},
</if>
</set>
where emp_id = #{empId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.wdzl.bean.Employee">
update emp
set emp_name = #{empName,jdbcType=VARCHAR},
gender = #{gender,jdbcType=CHAR},
email = #{email,jdbcType=VARCHAR},
dept_id = #{deptId,jdbcType=INTEGER}
where emp_id = #{empId,jdbcType=INTEGER}
</update>
</mapper>
三、CRUD
3.1列表查询
1.访问index.jsp页面
2.index.jsp页面发送查询员工列表的请求
3.EmpController接受请求,查询员工数据
4.跳转List.jsp页面,展示数据
3.2实现
1.修改index.jsp
2.创建Controller及相应的service及实现类
Controller
/**
* 员工相关操作控制层
*/
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@RequestMapping("/empList")
public String getEmps(@RequestParam(value = "pn",defaultValue = "1") Integer pn, Model model){
//List<Employee> list = employeeService.getAll();
//之前的方式
// model.addAttribute("List",list);
/**
* 第一个参数:起始页码
* 第二个参数:每页几条数据
*/
PageHelper.startPage(pn,10);
//插件后的查询紧跟就是分页查询
List<Employee> list = employeeService.getAll();
//将数据包装到pageInfo对象中:因为该对象中有分页所需的所有信息
PageInfo pageInfo = new PageInfo(list,5);
//将分页对象存储到model中
model.addAttribute("pageInfo",pageInfo);
return "List";
}
}
Service
public interface EmployeeService {
public List<Employee> getAll();
}
ServiceImpl
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
/**
* 获取员工列表
* @return
*/
@Override
public List<Employee> getAll() {
EmployeeExample employeeExample =new EmployeeExample();
employeeExample.setOrderByClause("emp_id");
List<Employee> list = employeeMapper.selectByExampleWithDept(employeeExample);
return list;
}
3.创建List.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
pageContext.setAttribute("path",request.getContextPath());
%>
<html>
<head>
<title>Title</title>
<!-- Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<!-- 标题-->
<div class="row">
<div class=".col-md-12"></div>
<h1>SSM-员工管理系统</h1>
<!-- 按钮-->
<div class="row">
<div class="col-md-4 col-md-offset-8">
<button type="button" class="btn btn-success">新增</button>
<button type="button" class="btn btn-danger">删除</button>
</div>
</div>
</div>
<!-- 表格-->
<div class="row">
<div class=".col-md-12">
<table class="table table-hover">
<tr>
<td>员工编号</td>
<td>姓名</td>
<td>性别</td>
<td>email</td>
<td>部门标签</td>
<td>操作</td>
</tr>
<c:forEach items="${pageInfo.list}" var="emp" >
<tr>
<td>${emp.empId}</td>
<td>${emp.empName}</td>
<td>${emp.gender}</td>
<td>${emp.email}</td>
<td>${emp.department.deptName}</td>
<td>
<button type="button" class="btn btn-success btn-sm">
<span class="glyphicon glyphicon-pencil"></span>
新增
</button>
<button type="button" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-trash"></span>
删除
</button>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<!--分页-->
<div class="row">
<!-- 分页信息-->
<div class="col-md-6" style="padding-top: 20px ">
当前第${pageInfo.pageNum}页,共${pageInfo.pages}页,共${pageInfo.total}条
</div>
<!-- 分页条-->
<div class="col-md-6" style="padding-left: 100px" >
<nav aria-label="Page navigation">
<ul class="pagination">
<li><a href="${path}/empList">首页</a></li>
<c:if test="${pageInfo.hasPreviousPage}">
<li>
<a href="${path}/empList?pn=${pageInfo.pageNum-1}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach items="${pageInfo.navigatepageNums}" var="pageNum">
<c:if test="${pageNum == pageInfo.pageNum}">
<li class="active"><a href="${path}/empList?pn=${pageNum}">${pageNum}</a></li>
</c:if>
<c:if test="${pageNum != pageInfo.pageNum}">
<li><a href="${path}/empList?pn=${pageNum}">${pageNum}</a></li>
</c:if>
</c:forEach>
<c:if test="${pageInfo.hasNextPage}">
<li>
<a href="${path}/empList?pn=${pageInfo.pageNum+1}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<li><a href="${path}/empList?pn=${pageInfo.pages}">末页</a></li>
</ul>
</nav>
</div>
</div>
</div>
</body>
</html>
3.2返回分页的JSON数据
步骤:
1.index.jsp页面发送Ajax请求,进行员工分页数据的查询
2.服务器将数据查询后,以JSON字符串格式返回给浏览器
3.3.浏览器接收到Json字符串,可以使用js解析Json,并将Js通过dom增删改的方式改变页面。
3.3添加员工功能
业务逻辑:
1.在index.jsp:点击"新增"按钮
2.弹出新增对话框
3.在对话框中显示从数据库查询出的员工的信息
4.添加完成后,自动跳转到最后一页
3.4修改员工功能
业务逻辑:
1.在index.jsp:点击"添加"按钮
2.弹出修改对话框
3.在对话框中显示从数据库查询出的员工的信息
3.5删除员工功能
业务逻辑:
1.在index.jsp:点击"删除"按钮
2.弹出提示框
3.Yes及删除,No不删除
3.6 业务实现
1.通用返回类
/**
* 通用返回类
*/
public class Msg {
private int code;//自定义状态码110-成功,120-失败
private String msg;//提示信息
private Map<String,Object> extend = new HashMap<>();//用户返回数据的通用定义格式
/**
* 快捷操作:成功
* @return
*/
public static Msg success(){
Msg result = new Msg();
result.setCode(110);
result.setMsg("成功");
return result;
}
/**
* 快捷操作:失败
* @return
*/
public static Msg fail(){
Msg result = new Msg();
result.setCode(120);
result.setMsg("失败");
return result;
}
/**
* 方便进行数据添加,也可以进行链式编程
* @return
*/
public Msg add(String key,Object value){
this.getExtend().put(key,value);
return this;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Map<String, Object> getExtend() {
return extend;
}
public void setExtend(Map<String, Object> extend) {
this.extend = extend;
}
}
2.EmployeeController
/**
* 员工相关操作控制层
*/
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@RequestMapping("/empList")
@ResponseBody
public Msg getEmpsWithJson(@RequestParam(value = "pn",defaultValue = "1") Integer pn){
PageHelper.startPage(pn,10);
//插件后的查询紧跟就是分页查询
List<Employee> list = employeeService.getAll();
//将数据包装到pageInfo对象中:因为该对象中有分页所需的所有信息
PageInfo pageInfo = new PageInfo(list,5);
return Msg.success().add("pageInfo",pageInfo);
}
/**
* 保存员工
* @param employee
* @return
* /emp/{id} GET:查询员工
* /emp POST:保存员工
* /emp/{id} PUT:修改员工
* /emp/{id} DELETE:删除员工
*/
@RequestMapping(value = "/emp",method = RequestMethod.POST)
@ResponseBody
public Msg saveEmp(@Valid Employee employee, BindingResult result){
// employeeService.saveEmp(employee);
// return Msg.success();
//1.判断
if (result.hasErrors()){
//1.获取字段错误对象,因为可能有多个错误,所以他要用集合接受
List<FieldError> errors = result.getFieldErrors();
//创建一个map集合,将错误对象存储到该集合中
Map<String,Object> map = new HashMap<>();
for (FieldError fieldError :errors){
//fieldError.getField();获取错误字段
System.out.println(fieldError.getField() +"------>"+employee.getEmpName()+"------>"+fieldError.getDefaultMessage());
//fieldError.getDefaultMessage();获取错误信息
//3.将错误字段存储到集合中
map.put(fieldError.getField(),fieldError.getDefaultMessage());
}
return Msg.fail().add("errorFileds",map);
}else {
employeeService.saveEmp(employee);
return Msg.success();
}
}
@RequestMapping("/checkName")
@ResponseBody
public Msg checkName(String empName){
boolean result = employeeService.checkName(empName);
if (result){
return Msg.success();
}else{
return Msg.fail();
}
}
@RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
@ResponseBody
public Msg getEmp(@PathVariable("id") Integer id){
Employee emp = employeeService.getEmp(id);
return Msg.success().add("emp",emp);
}
@RequestMapping(value = "/emp/{empId}",method = RequestMethod.PUT)
@ResponseBody
public Msg updateEmp(Employee employee){
employeeService.updateEmp(employee);
return Msg.success();
}
@RequestMapping(value = "/emp/{id}",method = RequestMethod.DELETE)
@ResponseBody
public Msg delEmp(@PathVariable("id") Integer id){
employeeService.deleteEmp(id);
return Msg.success();
}
}
3.DepartmentController
/**
* 部门相关操作控制层
*/
@Controller
public class DepartmentController {
@Autowired
private DepartmentService service;
@RequestMapping("/depts")
@ResponseBody
public Msg getDepts(){
List<Department> list=service.getDepts();
return Msg.success().add("depts",list);
}
}
4.EmployeeService及其实现类
public interface EmployeeService {
public List<Employee> getAll();
void saveEmp(Employee employee);
boolean checkName(String empName);
Employee getEmp(Integer id);
void updateEmp(Employee employee);
void deleteEmp(Integer id);
}
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
/**
* 获取员工列表
* @return
*/
@Override
public List<Employee> getAll() {
EmployeeExample employeeExample =new EmployeeExample();
employeeExample.setOrderByClause("emp_id");
List<Employee> list = employeeMapper.selectByExampleWithDept(employeeExample);
return list;
}
@Override
public void saveEmp(Employee employee) {
employeeMapper.insertSelective(employee);
}
/**
* 异步校验用户名
* @param empName
* @return
*/
@Override
public boolean checkName(String empName) {
EmployeeExample employeeExample = new EmployeeExample();
EmployeeExample.Criteria criteria = employeeExample.createCriteria();
criteria.andEmpNameEqualTo(empName);
long count = employeeMapper.countByExample(employeeExample);
return count == 0;
}
/**
* 获取员工信息
* @param id
* @return
*/
@Override
public Employee getEmp(Integer id) {
Employee employee = employeeMapper.selectByPrimaryKey(id);
return employee;
}
@Override
public void updateEmp(Employee employee) {
employeeMapper.updateByPrimaryKeySelective(employee);
}
@Override
public void deleteEmp(Integer id) {
employeeMapper.deleteByPrimaryKey(id);
}
}
5.DepartmentService及其实现类
public interface DepartmentService {
public List<Department> getDepts();
}
@Service
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
DepartmentMapper departmentMapper;
@Override
public List<Department> getDepts() {
return departmentMapper.selectByExample(null);
}
}
6.index.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--<jsp:forward page="/empList"></jsp:forward>--%>
<%
pageContext.setAttribute("path",request.getContextPath());
%>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- Bootstrap -->
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="modal fade" id="modal_update_emp" 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">姓名</label>
<div class="col-sm-10">
<p class="form-control-static" id="input_update_empName" name="empName"></p>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">姓别</label>
<div class="col-sm-10">
<div class="radio">
<label>
<input type="radio" name="gender" id="blankRadio3" value="男" checked>男
</label>
<label>
<input type="radio" name="gender" id="blankRadio4" value="女" >女
</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control glyphicon " id="input_update_empEmail" name="email" placeholder="Email">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">部门</label>
<div class="col-sm-5">
<select class="form-control" id="sel_update_dept" name="deptId"></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="btn_emp_update" >更新</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="myModal" 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" id="model_add_emp">
<form class="form-horizontal" >
<div class="form-group">
<label class="col-sm-2 control-label">姓名</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="input_empName" name="empName" placeholder="name">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">姓别</label>
<div class="col-sm-10">
<div class="radio">
<label>
<input type="radio" name="gender" id="blankRadio1" value="男" checked>男
</label>
<label>
<input type="radio" name="gender" id="blankRadio2" value="女" >女
</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="input_empEmail" name="email" placeholder="Email">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">部门</label>
<div class="col-sm-5">
<select class="form-control" id="sel_dept" name="deptId"></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="btn_emp_save" >保存</button>
</div>
</div>
</div>
</div>
<div class="container">
<!-- 标题-->
<div class="row">
<div class=".col-md-12"></div>
<h1>SSM-员工管理系统</h1>
<!-- 按钮-->
<div class="row">
<div class="col-md-4 col-md-offset-8">
<button type="button" class="btn btn-success" id="btn_add_emp">新增</button>
<button type="button" class="btn btn-danger">删除</button>
</div>
</div>
</div>
<!-- 表格-->
<div class="row">
<div class=".col-md-12">
<table class="table table-hover" id="emps_table">
<thead>
<tr>
<td>员工编号</td>
<td>姓名</td>
<td>性别</td>
<td>email</td>
<td>部门标签</td>
<td>操作</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!--分页-->
<div class="row">
<!-- 分页信息-->
<div class="col-md-6" style="padding-top: 20px" id="page_info_area">
</div>
<!-- 分页条-->
<div class="col-md-6" style="padding-left: 100px" id="page_nav_area" >
</div>
</div>
</div>
<script type="text/javascript">
var totalPage;
var currentPage;
//页面加载完成后,直接发送Ajax请求,得到分页数据
$(function (){
request_pageInfo(1);
});
//请求分页数据的方法
function request_pageInfo(pn){
$.ajax({
url: "/empList",
data: "pn="+pn,
type: "get",
success: function (result) {
//console.log(result)
//1.解析并显示员工信息
build_emps_table(result);
//2.解析并显示分页信息
build_page_info(result);
//3.解析并显示分页条
build_page_nav(result);
}
});
}
//构建员工列表的方法
function build_emps_table(result){
$("#emps_table tbody").empty();
var emps = result.extend.pageInfo.list;
$.each(emps,function (index,item){
//alert(item.empName);
var empId = $("<td></td>").append(item.empId);
var empName = $("<td></td>").append(item.empName);
var gender = $("<td></td>").append(item.gender);
var email = $("<td></td>").append(item.email);
var deptName = $("<td></td>").append(item.department.deptName);
var editBtn = $("<button></button>").addClass("btn btn-success btn-sm").attr("id","btn_update").append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑").attr("emp_id",item.empId);
var deleteBtn = $("<button></button>").addClass("btn btn-danger btn-sm").attr("id","btn_delete").append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除").attr("emp_id",item.empId);;
var buttonTd=$("<td></td>").append(editBtn).append(" ").append(deleteBtn);
$("<tr></tr>").append(empId)
.append(empName)
.append(gender)
.append(email)
.append(deptName)
.append(buttonTd)
.appendTo("#emps_table tbody")
});
}
//构建分页
function build_page_info(result){
//清空容器内容
$("#page_info_area").empty();
$("#page_info_area").append("当前第"+result.extend.pageInfo.pageNum+"页,共"+result.extend.pageInfo.pages+"页,共"+result.extend.pageInfo.total+"条");
totalPage=result.extend.pageInfo.pages;
currentPage=result.extend.pageInfo.pageNum;
}
//构建分页条
function build_page_nav(result){
//
$("#page_nav_area").empty();
//构建ul标签
var ul = $("<ul></ul>").addClass("pagination");
//构建固定显示的部分
var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
var prePageLi = $("<li></li>").append($("<a></a>").append("«").attr("href","#"));
if(result.extend.pageInfo.hasPreviousPage == false){
firstPageLi.addClass("disabled");
prePageLi.addClass("disabled");
}
var nextPageLi = $("<li></li>").append($("<a></a>").append("»").attr("href","#"));
var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
if(result.extend.pageInfo.hasNextPage == false){
nextPageLi.addClass("disabled");
lastPageLi.addClass("disabled");
}
//在ul中拼接首页和上一页
ul.append(firstPageLi).append(prePageLi);
//在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 (){
request_pageInfo(item);
});
//每循环一次,添加一个页码按钮
ul.append(numLi);
});
//循环结束后,拼接末页和下一页
ul.append(nextPageLi).append(lastPageLi);
//上一页,首页,末页,下一页
firstPageLi.click(function (){
request_pageInfo(1);
});
prePageLi.click(function (){
request_pageInfo(result.extend.pageInfo.pageNum - 1);
});
lastPageLi.click(function (){
request_pageInfo(result.extend.pageInfo.pages);
});
nextPageLi.click(function (){
request_pageInfo(result.extend.pageInfo.pageNum + 1);
});
//将ul添加到nav标签中
var navEle=$("<nav></nav>").append(ul);
//将nav拼接到div中
navEle.appendTo("#page_nav_area");
}
//给新增按钮绑定单击事件:弹出模态
$("#btn_add_emp").click(function (){
//1.发送ajax请求,查询部门信息,显示在下拉框
$("#sel_dept").empty();
getDepts("#sel_dept");
//2.弹出模态框
$("#myModal").modal({
backdrop:"static"
});
});
//获取部门信息
function getDepts(ele){
$.ajax({
url:"/depts",
type:"GET",
success:function(result){
//console.log(result)
$.each(result.extend.depts,function(index,item){
var optionEle = $("<option></option>").append(item.deptName).attr("value",item.deptId);
optionEle.appendTo(ele);
});
}
});
}
//保存按钮绑定单击事件
$("#btn_emp_save").click(function (){
//1.校验数据
// if (!validate_add_form()){
// return false;
// }
//2.将数据提交到服务器
// $.ajax({
// url:"/emp",
// type:"POST",
// data:$("#model_add_emp form").serialize(),
// success:function (result){
// //alert(result.msg);
// //保存成功关闭模态框
// $('#myModal').modal('hide');
// //跳转至最后一页
// request_pageInfo(totalPage*2);
//
// }
// })
$.ajax({
url:"/emp",
type:"POST",
data:$("#model_add_emp form").serialize(),
success:function (result){
$("#input_empName").parent().removeClass("has-success has-error");
$("#input_empName").next("span").empty();
$("#input_empEmail").parent().removeClass("has-success has-error");
$("#input_empEmail").next("span").empty();
if (result.code == 120){
if(result.extend.errorFileds.empName != undefined){
show_validate_msg("#input_empName","error",result.extend.errorFileds.empName);
}
if(result.extend.errorFileds.email != undefined){
show_validate_msg("#input_empEmail","error",result.extend.errorFileds.email);
}
}else if (result.code == 110){
//保存成功关闭模态框
$('#myModal').modal('hide');
// //跳转至最后一页
request_pageInfo(totalPage*2);
}
}
})
});
//校验表单数据
// function validate_add_form(){
// //通过正则表达式对表达数据进行校验
// //用户名
// var empName=$("#input_empName").val();
// var regName=/^[a-z0-9_-]{2,16}$/;
// if (!regName.test(empName)){
// //alert("用户名格式错误,必须是2-16位字符或数字组成");
// show_validate_msg("#input_empName","error","用户名格式错误,必须是2-16位字符或数字组成");
// return false;
// }else {
// show_validate_msg("#input_empName","success","");
// }
// //邮箱
// var email=$("#input_empEmail").val();
// var regEmail=/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
// if (!regEmail.test(email)){
// //alert("邮箱格式错误");
// show_validate_msg("#input_empEmail","error","邮箱格式错误");
// return false;
// }else {
// show_validate_msg("#input_empEmail","success","");
// }
//
// return true;
// }
/**
* 显示校验信息的方法
* @param ele 操作的元素
* @param status 校验状态
* @param msg 校验提示信息
*/
function show_validate_msg(ele,status,msg){
//1.清空class属性
$(ele).parent().removeClass("has-success has-error");
$(ele).next("span").removeClass("glyphicon glyphicon-ok");
if ("success" == status){
$(ele).parent().addClass("has-success");
$(ele).next("span").text(msg).addClass("glyphicon glyphicon-ok");
}else if ("error" == status){
$(ele).parent().addClass("has-error");
$(ele).next("span").text(msg).addClass("glyphicon glyphicon-remove");
}
}
//用户名异步校验
$("#input_empName").blur(function (){
var empName=$("#input_empName").val()
$.ajax({
url:"/checkName",
type:"GET",
data: "empName=" + empName,
success:function (result){
if (result.code == 120){
//不可用
show_validate_msg("#input_empName","error","用户名不可用")
}else if (result.code == 110){
//可用
show_validate_msg("#input_empName","success","用户名可用")
}
}
});
})
//调用修改模态框
$(document).on("click","#btn_update",function (){
//1.查出员工信息
getEmp($(this).attr("emp_id"));
//2.查出部门信息
$("#sel_update_dept").empty();
getDepts("#sel_update_dept");
//3.弹出模态框
$("#modal_update_emp").modal({
backdrop:"static"
});
});
//获取员工信息的方法
function getEmp(id){
$.ajax({
url:"/emp/" + id,
type:"GET",
success:function (result){
var empData = result.extend.emp;
$("#input_update_empName").text(empData.empName);
$("#modal_update_emp input[name=gender]").val([empData.gender]);
$("#input_update_empEmail").val(empData.email);
$("#modal_update_emp select").next("value").val(empData.deptId);
$("#btn_emp_update").attr("emp-id",empData.empId);
}
})
}
//点击更新按钮,更新员工信息
$("#btn_emp_update").click(function (){
$.ajax({
url:"/emp/"+$(this).attr("emp-id"),
type:"POST",
data:$("#modal_update_emp form").serialize()+"&_method=PUT",
success:function (result){
//关闭模态框
$('#modal_update_emp').modal('hide');
//跳转至当前页
request_pageInfo(currentPage);
}
})
})
//点击删除按钮,删除员工信息
$(document).on("click","#btn_delete",function (){
var empId = $(this).attr("emp_id");
if (confirm("确认删除"+empId+"吗?")){
//确认
$.ajax({
url:"/emp/"+empId,
type:"DELETE",
success:function (result){
request_pageInfo(currentPage);
}
});
}
});
</script>
</body>
</html>
3.7结果演示
1.查询出员工信息
2.添加功能演示
3.修改功能演示
4.删除功能演示