1、项目运行效果图
首页 末尾 增加 删除 修改
2、文件目录
3、pom.xml和web.xml
pom.xml
<project xmlns
="http://maven.apache.org/POM/4.0.0" xmlns
:xsi
="http://www.w3.org/2001/XMLSchema-instance" xsi
:schemaLocation
="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion
>
<groupId>com
.ssm
</groupId
>
<artifactId>Maven
-crud
</artifactId
>
<version>0.0.1-SNAPSHOT
</version
>
<packaging>war
</packaging
>
<!--引入项目依赖的jar包
-->
<!-- SpringMVC、Spring
-->
<!-- https
://mvnrepository
.com
/artifact
/org
.springframework
/spring
-webmvc
-->
<dependencies>
<!--引入pageHelper分页插件
-->
<dependency>
<groupId>com
.github
.pagehelper
</groupId
>
<artifactId>pagehelper
</artifactId
>
<version>5.0.0</version
>
</dependency
>
<!-- MBG
-->
<!-- 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
>
<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
>
</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</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,servlet
-api,junit)
-->
<!-- https
://mvnrepository
.com
/artifact
/jstl
/jstl
-->
<dependency>
<groupId>jstl
</groupId
>
<artifactId>jstl
</artifactId
>
<version>1.2</version
>
</dependency
>
<!-- https
://mvnrepository
.com
/artifact
/javax
.servlet
/javax
.servlet
-api
-->
<dependency>
<groupId>javax
.servlet
</groupId
>
<artifactId>javax
.servlet
-api
</artifactId
>
<version>3.0.1</version
>
<scope>provided
</scope
>
</dependency
>
<!-- junit
-->
<!-- https
://mvnrepository
.com
/artifact
/junit
/junit
-->
<dependency>
<groupId>junit
</groupId
>
<artifactId>junit
</artifactId
>
<version>4.12</version
>
</dependency
>
</dependencies
>
</project
>
web.xml
<?xml version
="1.0" encoding
="UTF-8"?>
<web
-app xmlns
:xsi
="http://www.w3.org/2001/XMLSchema-instance" xmlns
="http://xmlns.jcp.org/xml/ns/javaee" xsi
:schemaLocation
="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id
="WebApp_ID" version
="3.1">
<welcome
-file
-list
>
<welcome
-file
>index
.jsp
</welcome
-file
>
</welcome
-file
-list
>
<!--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
>
<!-- Map all requests to the DispatcherServlet
for handling
-->
<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
>
4、spring配置文件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
.xsd
http
://www
.springframework
.org
/schema
/context http
://www
.springframework
.org
/schema
/context
/spring
-context
-4.3.xsd
http
://www
.springframework
.org
/schema
/aop http
://www
.springframework
.org
/schema
/aop
/spring
-aop
-4.3.xsd
http
://www
.springframework
.org
/schema
/tx http
://www
.springframework
.org
/schema
/tx
/spring
-tx
-4.3.xsd"
>
<context
:component
-scan base
-package="com.ssm">
<context
:exclude
-filter type
="annotation" expression
="org.springframework.stereotype.Controller"/>
</context
:component
-scan
>
<!--spring的配置文件
-->
<context
:property
-placeholder location
="classpath:dbconfig.properties"/>
<bean id
="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name
="jdbcUrl" value
="${jdbc.jdbcUrl}"></property
>
<property name
="driverClass" value
="${jdbc.driverClass}"></property
>
<property name
="user" value
="${jdbc.user}"></property
>
<property name
="password" value
="${jdbc.password}"></property
>
</bean
>
<!-- 配置和mybatis的整合
-->
<bean id
="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定mybatis全局配置文件的位置
-->
<property name
="configLocation" value
="classpath:mybatis-config.xml"></property
>
<property name
="dataSource" ref
="pooledDataSource"></property
>
<!-- 指定mybatis,mapper文件的位置
-->
<property name
="mapperLocations" value
="classpath:mapper/*.xml"></property
>
</bean
>
<!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中
-->
<bean
class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描所有dao接口的实现,加入到ioc容器中
-->
<property name
="basePackage" value
="com.ssm.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.atguigu.crud.service..*(..))" id
="txPoint"/>
<!-- 配置事务增强
-->
<aop
:advisor advice
-ref
="txAdvice" pointcut
-ref
="txPoint"/>
</aop
:config
>
<!--配置事务增强,事务如何切入
-->
<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
>
5、c3p0数据源dbconfig.properties
jdbc
.jdbcUrl
=jdbc
:mysql
://localhost
:3306/ssm_crud
jdbc
.driverClass
=com
.mysql
.jdbc
.Driver
jdbc
.user
=root
jdbc
.password
=1141341095
6、mybatis配置文件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.ssm.crud.bean"/>
</typeAliases
>
<plugins>
<plugin interceptor
="com.github.pagehelper.PageInterceptor">
<!--分页参数合理化
-->
<property name
="reasonable" value
="true"/>
</plugin
>
</plugins
>
</configuration
>
7、springmvc配置文件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
:context
="http://www.springframework.org/schema/context"
xmlns
:mvc
="http://www.springframework.org/schema/mvc"
xsi
:schemaLocation
="http
://www
.springframework
.org
/schema
/mvc http
://www
.springframework
.org
/schema
/mvc
/spring
-mvc
-4.3.xsd
http
://www
.springframework
.org
/schema
/beans http
://www
.springframework
.org
/schema
/beans
/spring
-beans
.xsd
http
://www
.springframework
.org
/schema
/context http
://www
.springframework
.org
/schema
/context
/spring
-context
-4.3.xsd"
>
<!--springmvc的配置文件,包含网站的跳转逻辑的控制,配置
-->
<context
:component
-scan base
-package="com.ssm" 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
>
8、我用的是逆向工程生成bean、dao、mapper.xml
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>
<context id
="DB2Tables" targetRuntime
="MyBatis3">
<commentGenerator>
<property name
="suppressAllComments" value
="true" />
</commentGenerator
>
<!-- 配置数据库连接
-->
<jdbcConnection driverClass
="com.mysql.jdbc.Driver"
connectionURL
="jdbc:mysql://localhost:3306/ssm_crud" userId
="root"
password
="1141341095">
</jdbcConnection
>
<javaTypeResolver>
<property name
="forceBigDecimals" value
="false" />
</javaTypeResolver
>
<!-- 指定javaBean生成的位置
-->
<javaModelGenerator targetPackage
="com.ssm.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.ssm.crud.dao" targetProject
=".\src\main\java">
<property name
="enableSubPackages" value
="true" />
</javaClientGenerator
>
<!-- table指定每个表的生成策略
-->
<table tableName
="tbl_emp" domainObjectName
="Employee"></table
>
<table tableName
="tbl_dept" domainObjectName
="Department"></table
>
</context
>
</generatorConfiguration
>
MBGTest.java
package com
.ssm
.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
);
}
}
这样运行后会产生相关的文件。
9、bean目录下的java文件
package com
.ssm
.crud
.bean
;
public class Department {
private Integer deptId
;
private String deptName
;
public Department() {
super();
}
public Department(Integer deptId
, String deptName
) {
super();
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();
}
}
package com
.ssm
.crud
.bean
;
import java
.util
.ArrayList
;
import java
.util
.List
;
public class DepartmentExample {
protected String orderByClause
;
protected boolean distinct
;
protected List
<Criteria> oredCriteria
;
public DepartmentExample() {
oredCriteria
= new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause
) {
this.orderByClause
= orderByClause
;
}
public String
getOrderByClause() {
return orderByClause
;
}
public void setDistinct(boolean distinct
) {
this.distinct
= distinct
;
}
public boolean isDistinct() {
return distinct
;
}
public List
<Criteria> getOredCriteria() {
return oredCriteria
;
}
public void or(Criteria criteria
) {
oredCriteria
.add(criteria
);
}
public Criteria
or() {
Criteria criteria
= createCriteriaInternal();
oredCriteria
.add(criteria
);
return criteria
;
}
public Criteria
createCriteria() {
Criteria criteria
= createCriteriaInternal();
if (oredCriteria
.size() == 0) {
oredCriteria
.add(criteria
);
}
return criteria
;
}
protected Criteria
createCriteriaInternal() {
Criteria criteria
= new Criteria();
return criteria
;
}
public void clear() {
oredCriteria
.clear();
orderByClause
= null
;
distinct
= false;
}
protected abstract static class GeneratedCriteria {
protected List
<Criterion> criteria
;
protected GeneratedCriteria() {
super();
criteria
= new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria
.size() > 0;
}
public List
<Criterion> getAllCriteria() {
return criteria
;
}
public List
<Criterion> getCriteria() {
return criteria
;
}
protected void addCriterion(String condition
) {
if (condition
== null
) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria
.add(new Criterion(condition
));
}
protected void addCriterion(String condition
, Object value
, String property
) {
if (value
== null
) {
throw new RuntimeException("Value for " + property
+ " cannot be null");
}
criteria
.add(new Criterion(condition
, value
));
}
protected void addCriterion(String condition
, Object value1
, Object value2
, String property
) {
if (value1
== null
|| value2
== null
) {
throw new RuntimeException("Between values for " + property
+ " cannot be null");
}
criteria
.add(new Criterion(condition
, value1
, value2
));
}
public Criteria
andDeptIdIsNull() {
addCriterion("dept_id is null");
return (Criteria
) this;
}
public Criteria
andDeptIdIsNotNull() {
addCriterion("dept_id is not null");
return (Criteria
) this;
}
public Criteria
andDeptIdEqualTo(Integer value
) {
addCriterion("dept_id =", value
, "deptId");
return (Criteria
) this;
}
public Criteria
andDeptIdNotEqualTo(Integer value
) {
addCriterion("dept_id <>", value
, "deptId");
return (Criteria
) this;
}
public Criteria
andDeptIdGreaterThan(Integer value
) {
addCriterion("dept_id >", value
, "deptId");
return (Criteria
) this;
}
public Criteria
andDeptIdGreaterThanOrEqualTo(Integer value
) {
addCriterion("dept_id >=", value
, "deptId");
return (Criteria
) this;
}
public Criteria
andDeptIdLessThan(Integer value
) {
addCriterion("dept_id <", value
, "deptId");
return (Criteria
) this;
}
public Criteria
andDeptIdLessThanOrEqualTo(Integer value
) {
addCriterion("dept_id <=", value
, "deptId");
return (Criteria
) this;
}
public Criteria
andDeptIdIn(List
<Integer> values
) {
addCriterion("dept_id in", values
, "deptId");
return (Criteria
) this;
}
public Criteria
andDeptIdNotIn(List
<Integer> values
) {
addCriterion("dept_id not in", values
, "deptId");
return (Criteria
) this;
}
public Criteria
andDeptIdBetween(Integer value1
, Integer value2
) {
addCriterion("dept_id between", value1
, value2
, "deptId");
return (Criteria
) this;
}
public Criteria
andDeptIdNotBetween(Integer value1
, Integer value2
) {
addCriterion("dept_id not between", value1
, value2
, "deptId");
return (Criteria
) this;
}
public Criteria
andDeptNameIsNull() {
addCriterion("dept_name is null");
return (Criteria
) this;
}
public Criteria
andDeptNameIsNotNull() {
addCriterion("dept_name is not null");
return (Criteria
) this;
}
public Criteria
andDeptNameEqualTo(String value
) {
addCriterion("dept_name =", value
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameNotEqualTo(String value
) {
addCriterion("dept_name <>", value
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameGreaterThan(String value
) {
addCriterion("dept_name >", value
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameGreaterThanOrEqualTo(String value
) {
addCriterion("dept_name >=", value
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameLessThan(String value
) {
addCriterion("dept_name <", value
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameLessThanOrEqualTo(String value
) {
addCriterion("dept_name <=", value
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameLike(String value
) {
addCriterion("dept_name like", value
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameNotLike(String value
) {
addCriterion("dept_name not like", value
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameIn(List
<String> values
) {
addCriterion("dept_name in", values
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameNotIn(List
<String> values
) {
addCriterion("dept_name not in", values
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameBetween(String value1
, String value2
) {
addCriterion("dept_name between", value1
, value2
, "deptName");
return (Criteria
) this;
}
public Criteria
andDeptNameNotBetween(String value1
, String value2
) {
addCriterion("dept_name not between", value1
, value2
, "deptName");
return (Criteria
) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition
;
private Object value
;
private Object secondValue
;
private boolean noValue
;
private boolean singleValue
;
private boolean betweenValue
;
private boolean listValue
;
private String typeHandler
;
public String
getCondition() {
return condition
;
}
public Object
getValue() {
return value
;
}
public Object
getSecondValue() {
return secondValue
;
}
public boolean isNoValue() {
return noValue
;
}
public boolean isSingleValue() {
return singleValue
;
}
public boolean isBetweenValue() {
return betweenValue
;
}
public boolean isListValue() {
return listValue
;
}
public String
getTypeHandler() {
return typeHandler
;
}
protected Criterion(String condition
) {
super();
this.condition
= condition
;
this.typeHandler
= null
;
this.noValue
= true;
}
protected Criterion(String condition
, Object value
, String typeHandler
) {
super();
this.condition
= condition
;
this.value
= value
;
this.typeHandler
= typeHandler
;
if (value
instanceof List<?>) {
this.listValue
= true;
} else {
this.singleValue
= true;
}
}
protected Criterion(String condition
, Object value
) {
this(condition
, value
, null
);
}
protected Criterion(String condition
, Object value
, Object secondValue
, String typeHandler
) {
super();
this.condition
= condition
;
this.value
= value
;
this.secondValue
= secondValue
;
this.typeHandler
= typeHandler
;
this.betweenValue
= true;
}
protected Criterion(String condition
, Object value
, Object secondValue
) {
this(condition
, value
, secondValue
, null
);
}
}
}
package com
.ssm
.crud
.bean
;
import javax
.validation
.constraints
.Pattern
;
public class Employee {
private Integer empId
;
@Pattern(regexp
="(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})"
,message
="用户名必须是2-5位中文或者6-16位英文和数字的组合")
private String empName
;
private String gender
;
@Pattern(regexp
="^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$",
message
="邮箱格式不正确")
private String email
;
private Integer dId
;
private Department department
;
@Override
public String
toString() {
return "Employee [empId=" + empId
+ ", empName=" + empName
+ ", gender=" + gender
+ ", email=" + email
+ ", dId=" + dId
+ "]";
}
public Employee() {
super();
}
public Employee(Integer empId
, String empName
, String gender
, String email
,
Integer dId
) {
super();
this.empId
= empId
;
this.empName
= empName
;
this.gender
= gender
;
this.email
= email
;
this.dId
= dId
;
}
public Department
getDepartment() {
return department
;
}
public void setDepartment(Department department
) {
this.department
= department
;
}
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
getdId() {
return dId
;
}
public void setdId(Integer dId
) {
this.dId
= dId
;
}
}
package com
.ssm
.crud
.bean
;
import java
.util
.ArrayList
;
import java
.util
.List
;
public class EmployeeExample {
protected String orderByClause
;
protected boolean distinct
;
protected List
<Criteria> oredCriteria
;
public EmployeeExample() {
oredCriteria
= new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause
) {
this.orderByClause
= orderByClause
;
}
public String
getOrderByClause() {
return orderByClause
;
}
public void setDistinct(boolean distinct
) {
this.distinct
= distinct
;
}
public boolean isDistinct() {
return distinct
;
}
public List
<Criteria> getOredCriteria() {
return oredCriteria
;
}
public void or(Criteria criteria
) {
oredCriteria
.add(criteria
);
}
public Criteria
or() {
Criteria criteria
= createCriteriaInternal();
oredCriteria
.add(criteria
);
return criteria
;
}
public Criteria
createCriteria() {
Criteria criteria
= createCriteriaInternal();
if (oredCriteria
.size() == 0) {
oredCriteria
.add(criteria
);
}
return criteria
;
}
protected Criteria
createCriteriaInternal() {
Criteria criteria
= new Criteria();
return criteria
;
}
public void clear() {
oredCriteria
.clear();
orderByClause
= null
;
distinct
= false;
}
protected abstract static class GeneratedCriteria {
protected List
<Criterion> criteria
;
protected GeneratedCriteria() {
super();
criteria
= new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria
.size() > 0;
}
public List
<Criterion> getAllCriteria() {
return criteria
;
}
public List
<Criterion> getCriteria() {
return criteria
;
}
protected void addCriterion(String condition
) {
if (condition
== null
) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria
.add(new Criterion(condition
));
}
protected void addCriterion(String condition
, Object value
, String property
) {
if (value
== null
) {
throw new RuntimeException("Value for " + property
+ " cannot be null");
}
criteria
.add(new Criterion(condition
, value
));
}
protected void addCriterion(String condition
, Object value1
, Object value2
, String property
) {
if (value1
== null
|| value2
== null
) {
throw new RuntimeException("Between values for " + property
+ " cannot be null");
}
criteria
.add(new Criterion(condition
, value1
, value2
));
}
public Criteria
andEmpIdIsNull() {
addCriterion("emp_id is null");
return (Criteria
) this;
}
public Criteria
andEmpIdIsNotNull() {
addCriterion("emp_id is not null");
return (Criteria
) this;
}
public Criteria
andEmpIdEqualTo(Integer value
) {
addCriterion("emp_id =", value
, "empId");
return (Criteria
) this;
}
public Criteria
andEmpIdNotEqualTo(Integer value
) {
addCriterion("emp_id <>", value
, "empId");
return (Criteria
) this;
}
public Criteria
andEmpIdGreaterThan(Integer value
) {
addCriterion("emp_id >", value
, "empId");
return (Criteria
) this;
}
public Criteria
andEmpIdGreaterThanOrEqualTo(Integer value
) {
addCriterion("emp_id >=", value
, "empId");
return (Criteria
) this;
}
public Criteria
andEmpIdLessThan(Integer value
) {
addCriterion("emp_id <", value
, "empId");
return (Criteria
) this;
}
public Criteria
andEmpIdLessThanOrEqualTo(Integer value
) {
addCriterion("emp_id <=", value
, "empId");
return (Criteria
) this;
}
public Criteria
andEmpIdIn(List
<Integer> values
) {
addCriterion("emp_id in", values
, "empId");
return (Criteria
) this;
}
public Criteria
andEmpIdNotIn(List
<Integer> values
) {
addCriterion("emp_id not in", values
, "empId");
return (Criteria
) this;
}
public Criteria
andEmpIdBetween(Integer value1
, Integer value2
) {
addCriterion("emp_id between", value1
, value2
, "empId");
return (Criteria
) this;
}
public Criteria
andEmpIdNotBetween(Integer value1
, Integer value2
) {
addCriterion("emp_id not between", value1
, value2
, "empId");
return (Criteria
) this;
}
public Criteria
andEmpNameIsNull() {
addCriterion("emp_name is null");
return (Criteria
) this;
}
public Criteria
andEmpNameIsNotNull() {
addCriterion("emp_name is not null");
return (Criteria
) this;
}
public Criteria
andEmpNameEqualTo(String value
) {
addCriterion("emp_name =", value
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameNotEqualTo(String value
) {
addCriterion("emp_name <>", value
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameGreaterThan(String value
) {
addCriterion("emp_name >", value
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameGreaterThanOrEqualTo(String value
) {
addCriterion("emp_name >=", value
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameLessThan(String value
) {
addCriterion("emp_name <", value
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameLessThanOrEqualTo(String value
) {
addCriterion("emp_name <=", value
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameLike(String value
) {
addCriterion("emp_name like", value
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameNotLike(String value
) {
addCriterion("emp_name not like", value
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameIn(List
<String> values
) {
addCriterion("emp_name in", values
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameNotIn(List
<String> values
) {
addCriterion("emp_name not in", values
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameBetween(String value1
, String value2
) {
addCriterion("emp_name between", value1
, value2
, "empName");
return (Criteria
) this;
}
public Criteria
andEmpNameNotBetween(String value1
, String value2
) {
addCriterion("emp_name not between", value1
, value2
, "empName");
return (Criteria
) this;
}
public Criteria
andGenderIsNull() {
addCriterion("gender is null");
return (Criteria
) this;
}
public Criteria
andGenderIsNotNull() {
addCriterion("gender is not null");
return (Criteria
) this;
}
public Criteria
andGenderEqualTo(String value
) {
addCriterion("gender =", value
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderNotEqualTo(String value
) {
addCriterion("gender <>", value
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderGreaterThan(String value
) {
addCriterion("gender >", value
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderGreaterThanOrEqualTo(String value
) {
addCriterion("gender >=", value
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderLessThan(String value
) {
addCriterion("gender <", value
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderLessThanOrEqualTo(String value
) {
addCriterion("gender <=", value
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderLike(String value
) {
addCriterion("gender like", value
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderNotLike(String value
) {
addCriterion("gender not like", value
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderIn(List
<String> values
) {
addCriterion("gender in", values
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderNotIn(List
<String> values
) {
addCriterion("gender not in", values
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderBetween(String value1
, String value2
) {
addCriterion("gender between", value1
, value2
, "gender");
return (Criteria
) this;
}
public Criteria
andGenderNotBetween(String value1
, String value2
) {
addCriterion("gender not between", value1
, value2
, "gender");
return (Criteria
) this;
}
public Criteria
andEmailIsNull() {
addCriterion("email is null");
return (Criteria
) this;
}
public Criteria
andEmailIsNotNull() {
addCriterion("email is not null");
return (Criteria
) this;
}
public Criteria
andEmailEqualTo(String value
) {
addCriterion("email =", value
, "email");
return (Criteria
) this;
}
public Criteria
andEmailNotEqualTo(String value
) {
addCriterion("email <>", value
, "email");
return (Criteria
) this;
}
public Criteria
andEmailGreaterThan(String value
) {
addCriterion("email >", value
, "email");
return (Criteria
) this;
}
public Criteria
andEmailGreaterThanOrEqualTo(String value
) {
addCriterion("email >=", value
, "email");
return (Criteria
) this;
}
public Criteria
andEmailLessThan(String value
) {
addCriterion("email <", value
, "email");
return (Criteria
) this;
}
public Criteria
andEmailLessThanOrEqualTo(String value
) {
addCriterion("email <=", value
, "email");
return (Criteria
) this;
}
public Criteria
andEmailLike(String value
) {
addCriterion("email like", value
, "email");
return (Criteria
) this;
}
public Criteria
andEmailNotLike(String value
) {
addCriterion("email not like", value
, "email");
return (Criteria
) this;
}
public Criteria
andEmailIn(List
<String> values
) {
addCriterion("email in", values
, "email");
return (Criteria
) this;
}
public Criteria
andEmailNotIn(List
<String> values
) {
addCriterion("email not in", values
, "email");
return (Criteria
) this;
}
public Criteria
andEmailBetween(String value1
, String value2
) {
addCriterion("email between", value1
, value2
, "email");
return (Criteria
) this;
}
public Criteria
andEmailNotBetween(String value1
, String value2
) {
addCriterion("email not between", value1
, value2
, "email");
return (Criteria
) this;
}
public Criteria
andDIdIsNull() {
addCriterion("d_id is null");
return (Criteria
) this;
}
public Criteria
andDIdIsNotNull() {
addCriterion("d_id is not null");
return (Criteria
) this;
}
public Criteria
andDIdEqualTo(Integer value
) {
addCriterion("d_id =", value
, "dId");
return (Criteria
) this;
}
public Criteria
andDIdNotEqualTo(Integer value
) {
addCriterion("d_id <>", value
, "dId");
return (Criteria
) this;
}
public Criteria
andDIdGreaterThan(Integer value
) {
addCriterion("d_id >", value
, "dId");
return (Criteria
) this;
}
public Criteria
andDIdGreaterThanOrEqualTo(Integer value
) {
addCriterion("d_id >=", value
, "dId");
return (Criteria
) this;
}
public Criteria
andDIdLessThan(Integer value
) {
addCriterion("d_id <", value
, "dId");
return (Criteria
) this;
}
public Criteria
andDIdLessThanOrEqualTo(Integer value
) {
addCriterion("d_id <=", value
, "dId");
return (Criteria
) this;
}
public Criteria
andDIdIn(List
<Integer> values
) {
addCriterion("d_id in", values
, "dId");
return (Criteria
) this;
}
public Criteria
andDIdNotIn(List
<Integer> values
) {
addCriterion("d_id not in", values
, "dId");
return (Criteria
) this;
}
public Criteria
andDIdBetween(Integer value1
, Integer value2
) {
addCriterion("d_id between", value1
, value2
, "dId");
return (Criteria
) this;
}
public Criteria
andDIdNotBetween(Integer value1
, Integer value2
) {
addCriterion("d_id not between", value1
, value2
, "dId");
return (Criteria
) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition
;
private Object value
;
private Object secondValue
;
private boolean noValue
;
private boolean singleValue
;
private boolean betweenValue
;
private boolean listValue
;
private String typeHandler
;
public String
getCondition() {
return condition
;
}
public Object
getValue() {
return value
;
}
public Object
getSecondValue() {
return secondValue
;
}
public boolean isNoValue() {
return noValue
;
}
public boolean isSingleValue() {
return singleValue
;
}
public boolean isBetweenValue() {
return betweenValue
;
}
public boolean isListValue() {
return listValue
;
}
public String
getTypeHandler() {
return typeHandler
;
}
protected Criterion(String condition
) {
super();
this.condition
= condition
;
this.typeHandler
= null
;
this.noValue
= true;
}
protected Criterion(String condition
, Object value
, String typeHandler
) {
super();
this.condition
= condition
;
this.value
= value
;
this.typeHandler
= typeHandler
;
if (value
instanceof List<?>) {
this.listValue
= true;
} else {
this.singleValue
= true;
}
}
protected Criterion(String condition
, Object value
) {
this(condition
, value
, null
);
}
protected Criterion(String condition
, Object value
, Object secondValue
, String typeHandler
) {
super();
this.condition
= condition
;
this.value
= value
;
this.secondValue
= secondValue
;
this.typeHandler
= typeHandler
;
this.betweenValue
= true;
}
protected Criterion(String condition
, Object value
, Object secondValue
) {
this(condition
, value
, secondValue
, null
);
}
}
}
package com
.ssm
.crud
.bean
;
import java
.util
.HashMap
;
import java
.util
.Map
;
public class Msg {
private int code
;
private String msg
;
private Map
<String, Object> extend
= new HashMap<String, Object>();
public static Msg
success(){
Msg result
= new Msg();
result
.setCode(100);
result
.setMsg("处理成功!");
return result
;
}
public static Msg
fail(){
Msg result
= new Msg();
result
.setCode(200);
result
.setMsg("处理失败!");
return result
;
}
public 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
;
}
}
10、controller目录下的java文件
package com
.ssm
.crud
.controller
;
import java
.util
.List
;
import org
.springframework
.beans
.factory
.annotation
.Autowired
;
import org
.springframework
.stereotype
.Controller
;
import org
.springframework
.web
.bind
.annotation
.RequestMapping
;
import org
.springframework
.web
.bind
.annotation
.ResponseBody
;
import com
.ssm
.crud
.bean
.Department
;
import com
.ssm
.crud
.bean
.Msg
;
import com
.ssm
.crud
.service
.DepartmentService
;
@Controller
public class DepartmentController {
@Autowired
private DepartmentService departmentService
;
@RequestMapping("/depts")
@ResponseBody
public Msg
getDepts(){
List
<Department> list
= departmentService
.getDepts();
return Msg
.success().add("depts", list
);
}
}
package com
.ssm
.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
.ssm
.crud
.bean
.Employee
;
import com
.ssm
.crud
.bean
.Msg
;
import com
.ssm
.crud
.service
.EmployeeService
;
import com
.github
.pagehelper
.PageHelper
;
import com
.github
.pagehelper
.PageInfo
;
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService
;
@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("-");
for (String string
: str_ids
) {
del_ids
.add(Integer
.parseInt(string
));
}
employeeService
.deleteBatch(del_ids
);
}else{
Integer id
= Integer
.parseInt(ids
);
employeeService
.deleteEmp(id
);
}
return Msg
.success();
}
@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() ;
}
@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
);
}
@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", "用户名不可用");
}
}
@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();
}
}
@RequestMapping("/emps")
@ResponseBody
public Msg
getEmpsWithJson(
@RequestParam(value
= "pn", defaultValue
= "1") Integer pn
) {
PageHelper
.startPage(pn
, 5);
List
<Employee> emps
= employeeService
.getAll();
@SuppressWarnings({ "rawtypes", "unchecked" })
PageInfo page
= new PageInfo(emps
, 5);
return Msg
.success().add("pageInfo", page
);
}
public String
getEmps(
@RequestParam(value
= "pn", defaultValue
= "1") Integer pn
,
Model model
) {
PageHelper
.startPage(pn
, 5);
List
<Employee> emps
= employeeService
.getAll();
@SuppressWarnings({ "rawtypes", "unchecked" })
PageInfo page
= new PageInfo(emps
, 5);
model
.addAttribute("pageInfo", page
);
return "list";
}
}
11、dao目录下的java文件
package com
.ssm
.crud
.dao
;
import com
.ssm
.crud
.bean
.Department
;
import com
.ssm
.crud
.bean
.DepartmentExample
;
import java
.util
.List
;
import org
.apache
.ibatis
.annotations
.Param
;
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
);
}
package com
.ssm
.crud
.dao
;
import com
.ssm
.crud
.bean
.Employee
;
import com
.ssm
.crud
.bean
.EmployeeExample
;
import java
.util
.List
;
import org
.apache
.ibatis
.annotations
.Param
;
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
);
}
12、service目录下的java文件
package com
.ssm
.crud
.service
;
import java
.util
.List
;
import org
.springframework
.beans
.factory
.annotation
.Autowired
;
import org
.springframework
.stereotype
.Service
;
import com
.ssm
.crud
.bean
.Department
;
import com
.ssm
.crud
.dao
.DepartmentMapper
;
@Service
public class DepartmentService {
@Autowired
private DepartmentMapper departmentMapper
;
public List
<Department> getDepts() {
List
<Department> list
= departmentMapper
.selectByExample(null
);
return list
;
}
}
package com
.ssm
.crud
.service
;
import java
.util
.List
;
import org
.springframework
.beans
.factory
.annotation
.Autowired
;
import org
.springframework
.stereotype
.Service
;
import com
.ssm
.crud
.bean
.Employee
;
import com
.ssm
.crud
.bean
.EmployeeExample
;
import com
.ssm
.crud
.bean
.EmployeeExample
.Criteria
;
import com
.ssm
.crud
.dao
.EmployeeMapper
;
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper
;
public List
<Employee> getAll() {
return employeeMapper
.selectByExampleWithDept(null
);
}
public void saveEmp(Employee employee
) {
employeeMapper
.insertSelective(employee
);
}
public boolean checkUser(String empName
) {
EmployeeExample example
= new EmployeeExample();
Criteria criteria
= example
.createCriteria();
criteria
.andEmpNameEqualTo(empName
);
long count
= employeeMapper
.countByExample(example
);
return count
== 0;
}
public Employee
getEmp(Integer id
) {
Employee employee
= employeeMapper
.selectByPrimaryKey(id
);
return employee
;
}
public void updateEmp(Employee employee
) {
employeeMapper
.updateByPrimaryKeySelective(employee
);
}
public void deleteEmp(Integer id
) {
employeeMapper
.deleteByPrimaryKey(id
);
}
public void deleteBatch(List
<Integer> ids
) {
EmployeeExample example
= new EmployeeExample();
Criteria criteria
= example
.createCriteria();
criteria
.andEmpIdIn(ids
);
employeeMapper
.deleteByExample(example
);
}
}
13、mapper目录下的xml文件
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.ssm.crud.dao.DepartmentMapper">
<resultMap id
="BaseResultMap" type
="com.ssm.crud.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.ssm.crud.bean.DepartmentExample" resultMap
="BaseResultMap">
select
<if test
="distinct">
distinct
</if>
<include refid
="Base_Column_List" />
from tbl_dept
<if test
="_parameter != null">
<include refid
="Example_Where_Clause" />
</if>
<if test
="orderByClause != null">
order by $
{orderByClause
}
</if>
</select
>
<select id
="selectByPrimaryKey" parameterType
="java.lang.Integer" resultMap
="BaseResultMap">
select
<include refid
="Base_Column_List" />
from tbl_dept
where dept_id
= #
{deptId
,jdbcType
=INTEGER
}
</select
>
<delete id
="deleteByPrimaryKey" parameterType
="java.lang.Integer">
delete from tbl_dept
where dept_id
= #
{deptId
,jdbcType
=INTEGER
}
</delete
>
<delete id
="deleteByExample" parameterType
="com.ssm.crud.bean.DepartmentExample">
delete from tbl_dept
<if test
="_parameter != null">
<include refid
="Example_Where_Clause" />
</if>
</delete
>
<insert id
="insert" parameterType
="com.ssm.crud.bean.Department">
insert into tbl_dept
(dept_id
, dept_name
)
values
(#
{deptId
,jdbcType
=INTEGER
}, #
{deptName
,jdbcType
=VARCHAR
})
</insert
>
<insert id
="insertSelective" parameterType
="com.ssm.crud.bean.Department">
insert into tbl_dept
<trim prefix
="(" suffix
=")" suffixOverrides
=",">
<if test
="deptId != null">
dept_id
,
</if>
<if test
="deptName != null">
dept_name
,
</if>
</trim
>
<trim prefix
="values (" suffix
=")" suffixOverrides
=",">
<if test
="deptId != null">
#
{deptId
,jdbcType
=INTEGER
},
</if>
<if test
="deptName != null">
#
{deptName
,jdbcType
=VARCHAR
},
</if>
</trim
>
</insert
>
<select id
="countByExample" parameterType
="com.ssm.crud.bean.DepartmentExample" resultType
="java.lang.Long">
select
count(*) from tbl_dept
<if test
="_parameter != null">
<include refid
="Example_Where_Clause" />
</if>
</select
>
<update id
="updateByExampleSelective" parameterType
="map">
update tbl_dept
<set>
<if test
="record.deptId != null">
dept_id
= #
{record
.deptId
,jdbcType
=INTEGER
},
</if>
<if test
="record.deptName != null">
dept_name
= #
{record
.deptName
,jdbcType
=VARCHAR
},
</if>
</set
>
<if test
="_parameter != null">
<include refid
="Update_By_Example_Where_Clause" />
</if>
</update
>
<update id
="updateByExample" parameterType
="map">
update tbl_dept
set dept_id
= #
{record
.deptId
,jdbcType
=INTEGER
},
dept_name
= #
{record
.deptName
,jdbcType
=VARCHAR
}
<if test
="_parameter != null">
<include refid
="Update_By_Example_Where_Clause" />
</if>
</update
>
<update id
="updateByPrimaryKeySelective" parameterType
="com.ssm.crud.bean.Department">
update tbl_dept
<set>
<if test
="deptName != null">
dept_name
= #
{deptName
,jdbcType
=VARCHAR
},
</if>
</set
>
where dept_id
= #
{deptId
,jdbcType
=INTEGER
}
</update
>
<update id
="updateByPrimaryKey" parameterType
="com.ssm.crud.bean.Department">
update tbl_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.ssm.crud.dao.EmployeeMapper">
<resultMap id
="BaseResultMap" type
="com.ssm.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" />
</resultMap
>
<resultMap type
="com.ssm.crud.bean.Employee" id
="WithDeptResultMap">
<id column
="emp_id" jdbcType
="INTEGER" property
="empId" />
<result column
="emp_name" jdbcType
="VARCHAR" property
="empName" />
<result column
="gender" jdbcType
="CHAR" property
="gender" />
<result column
="email" jdbcType
="VARCHAR" property
="email" />
<result column
="d_id" jdbcType
="INTEGER" property
="dId" />
<!-- 指定联合查询出的部门字段的封装
-->
<association property
="department" javaType
="com.ssm.crud.bean.Department">
<id column
="dept_id" property
="deptId"/>
<result column
="dept_name" property
="deptName"/>
</association
>
</resultMap
>
<sql id
="Example_Where_Clause">
<where>
<foreach collection
="oredCriteria" item
="criteria" separator
="or">
<if test
="criteria.valid">
<trim prefix
="(" prefixOverrides
="and" suffix
=")">
<foreach collection
="criteria.criteria" item
="criterion">
<choose>
<when test
="criterion.noValue">
and $
{criterion
.condition
}
</when
>
<when test
="criterion.singleValue">
and $
{criterion
.condition
} #
{criterion
.value
}
</when
>
<when test
="criterion.betweenValue">
and $
{criterion
.condition
} #
{criterion
.value
} and #
{criterion
.secondValue
}
</when
>
<when test
="criterion.listValue">
and $
{criterion
.condition
}
<foreach close
=")" collection
="criterion.value" item
="listItem" open
="(" separator
=",">
#
{listItem
}
</foreach
>
</when
>
</choose
>
</foreach
>
</trim
>
</if>
</foreach
>
</where
>
</sql
>
<sql id
="Update_By_Example_Where_Clause">
<where>
<foreach collection
="example.oredCriteria" item
="criteria" separator
="or">
<if test
="criteria.valid">
<trim prefix
="(" prefixOverrides
="and" suffix
=")">
<foreach collection
="criteria.criteria" item
="criterion">
<choose>
<when test
="criterion.noValue">
and $
{criterion
.condition
}
</when
>
<when test
="criterion.singleValue">
and $
{criterion
.condition
} #
{criterion
.value
}
</when
>
<when test
="criterion.betweenValue">
and $
{criterion
.condition
} #
{criterion
.value
} and #
{criterion
.secondValue
}
</when
>
<when test
="criterion.listValue">
and $
{criterion
.condition
}
<foreach close
=")" collection
="criterion.value" item
="listItem" open
="(" separator
=",">
#
{listItem
}
</foreach
>
</when
>
</choose
>
</foreach
>
</trim
>
</if>
</foreach
>
</where
>
</sql
>
<sql id
="Base_Column_List">
emp_id
, emp_name
, gender
, email
, d_id
</sql
>
<sql id
="WithDept_Column_List">
e
.emp_id
, e
.emp_name
, e
.gender
, e
.email
, e
.d_id
,d
.dept_id
,d
.dept_name
</sql
>
<!-- List
<Employee> selectByExampleWithDept(EmployeeExample example
);
Employee
selectByPrimaryKeyWithDept(Integer empId
);
-->
<!-- 查询员工同时带部门信息
-->
<select id
="selectByExampleWithDept" resultMap
="WithDeptResultMap">
select
<if test
="distinct">
distinct
</if>
<include refid
="WithDept_Column_List" />
FROM tbl_emp e
left join tbl_dept d on e
.`d_id`
=d
.`dept_id`
<if test
="_parameter != null">
<include refid
="Example_Where_Clause" />
</if>
<if test
="orderByClause != null">
order by $
{orderByClause
}
</if>
</select
>
<select id
="selectByPrimaryKeyWithDept" resultMap
="WithDeptResultMap">
select
<include refid
="WithDept_Column_List" />
FROM tbl_emp e
left join tbl_dept d on e
.`d_id`
=d
.`dept_id`
where emp_id
= #
{empId
,jdbcType
=INTEGER
}
</select
>
<!-- 查询员工不带部门信息的
-->
<select id
="selectByExample" parameterType
="com.ssm.crud.bean.EmployeeExample" resultMap
="BaseResultMap">
select
<if test
="distinct">
distinct
</if>
<include refid
="Base_Column_List" />
from tbl_emp
<if test
="_parameter != null">
<include refid
="Example_Where_Clause" />
</if>
<if test
="orderByClause != null">
order by $
{orderByClause
}
</if>
</select
>
<select id
="selectByPrimaryKey" parameterType
="java.lang.Integer" resultMap
="BaseResultMap">
select
<include refid
="Base_Column_List" />
from tbl_emp
where emp_id
= #
{empId
,jdbcType
=INTEGER
}
</select
>
<delete id
="deleteByPrimaryKey" parameterType
="java.lang.Integer">
delete from tbl_emp
where emp_id
= #
{empId
,jdbcType
=INTEGER
}
</delete
>
<delete id
="deleteByExample" parameterType
="com.ssm.crud.bean.EmployeeExample">
delete from tbl_emp
<if test
="_parameter != null">
<include refid
="Example_Where_Clause" />
</if>
</delete
>
<insert id
="insert" parameterType
="com.ssm.crud.bean.Employee">
insert into tbl_emp
(emp_id
, emp_name
, gender
,
email
, d_id
)
values
(#
{empId
,jdbcType
=INTEGER
}, #
{empName
,jdbcType
=VARCHAR
}, #
{gender
,jdbcType
=CHAR
},
#
{email
,jdbcType
=VARCHAR
}, #
{dId
,jdbcType
=INTEGER
})
</insert
>
<insert id
="insertSelective" parameterType
="com.ssm.crud.bean.Employee">
insert into tbl_emp
<trim prefix
="(" suffix
=")" suffixOverrides
=",">
<if test
="empId != null">
emp_id
,
</if>
<if test
="empName != null">
emp_name
,
</if>
<if test
="gender != null">
gender
,
</if>
<if test
="email != null">
email
,
</if>
<if test
="dId != null">
d_id
,
</if>
</trim
>
<trim prefix
="values (" suffix
=")" suffixOverrides
=",">
<if test
="empId != null">
#
{empId
,jdbcType
=INTEGER
},
</if>
<if test
="empName != null">
#
{empName
,jdbcType
=VARCHAR
},
</if>
<if test
="gender != null">
#
{gender
,jdbcType
=CHAR
},
</if>
<if test
="email != null">
#
{email
,jdbcType
=VARCHAR
},
</if>
<if test
="dId != null">
#
{dId
,jdbcType
=INTEGER
},
</if>
</trim
>
</insert
>
<select id
="countByExample" parameterType
="com.ssm.crud.bean.EmployeeExample" resultType
="java.lang.Long">
select
count(*) from tbl_emp
<if test
="_parameter != null">
<include refid
="Example_Where_Clause" />
</if>
</select
>
<update id
="updateByExampleSelective" parameterType
="map">
update tbl_emp
<set>
<if test
="record.empId != null">
emp_id
= #
{record
.empId
,jdbcType
=INTEGER
},
</if>
<if test
="record.empName != null">
emp_name
= #
{record
.empName
,jdbcType
=VARCHAR
},
</if>
<if test
="record.gender != null">
gender
= #
{record
.gender
,jdbcType
=CHAR
},
</if>
<if test
="record.email != null">
email
= #
{record
.email
,jdbcType
=VARCHAR
},
</if>
<if test
="record.dId != null">
d_id
= #
{record
.dId
,jdbcType
=INTEGER
},
</if>
</set
>
<if test
="_parameter != null">
<include refid
="Update_By_Example_Where_Clause" />
</if>
</update
>
<update id
="updateByExample" parameterType
="map">
update tbl_emp
set emp_id
= #
{record
.empId
,jdbcType
=INTEGER
},
emp_name
= #
{record
.empName
,jdbcType
=VARCHAR
},
gender
= #
{record
.gender
,jdbcType
=CHAR
},
email
= #
{record
.email
,jdbcType
=VARCHAR
},
d_id
= #
{record
.dId
,jdbcType
=INTEGER
}
<if test
="_parameter != null">
<include refid
="Update_By_Example_Where_Clause" />
</if>
</update
>
<update id
="updateByPrimaryKeySelective" parameterType
="com.ssm.crud.bean.Employee">
update tbl_emp
<set>
<if test
="empName != null">
emp_name
= #
{empName
,jdbcType
=VARCHAR
},
</if>
<if test
="gender != null">
gender
= #
{gender
,jdbcType
=CHAR
},
</if>
<if test
="email != null">
email
= #
{email
,jdbcType
=VARCHAR
},
</if>
<if test
="dId != null">
d_id
= #
{dId
,jdbcType
=INTEGER
},
</if>
</set
>
where emp_id
= #
{empId
,jdbcType
=INTEGER
}
</update
>
<update id
="updateByPrimaryKey" parameterType
="com.ssm.crud.bean.Employee">
update tbl_emp
set emp_name
= #
{empName
,jdbcType
=VARCHAR
},
gender
= #
{gender
,jdbcType
=CHAR
},
email
= #
{email
,jdbcType
=VARCHAR
},
d_id
= #
{dId
,jdbcType
=INTEGER
}
where emp_id
= #
{empId
,jdbcType
=INTEGER
}
</update
>
</mapper
>
14、静态资源文件是可以从网上下载的,也可以从我的源码中直接取
list.jsp
<%@ page language
="java" contentType
="text/html; charset=UTF-8"
pageEncoding
="UTF-8"%>
<%@taglib uri
="http://java.sun.com/jsp/jstl/core" prefix
="c"%>
<!DOCTYPE html PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http
-equiv
="Content-Type" content
="text/html; charset=UTF-8">
<title>员工列表
</title
>
<%
pageContext
.setAttribute("APP_PATH", request
.getContextPath());
%>
<!-- web路径:
不以
/开始的相对路径,找资源,以当前资源的路径为基准,经常容易出问题。
以
/开始的相对路径,找资源,以服务器的路径为标准
(http
://localhost
:3306);需要加上项目名
http
://localhost
:3306/crud
-->
<script type
="text/javascript"
src
="${APP_PATH }/static/js/jquery-1.12.4.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 btn-primary btn-sm">
<span
class="glyphicon glyphicon-pencil" aria
-hidden
="true"></span
>
编辑
</button
>
<button
class="btn btn-danger btn-sm">
<span
class="glyphicon glyphicon-trash" aria
-hidden
="true"></span
>
删除
</button
>
</th
>
</tr
>
</c
:forEach
>
</table
>
</div
>
</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
>
</body
>
</html
>
index.jsp
<%@ page language
="java" contentType
="text/html; charset=UTF-8"
pageEncoding
="UTF-8"%>
<%@taglib uri
="http://java.sun.com/jsp/jstl/core" prefix
="c"%>
<!DOCTYPE html PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http
-equiv
="Content-Type" content
="text/html; charset=UTF-8">
<title>员工列表
</title
>
<%
pageContext
.setAttribute("APP_PATH", request
.getContextPath());
%>
<!-- web路径:
不以
/开始的相对路径,找资源,以当前资源的路径为基准,经常容易出问题。
以
/开始的相对路径,找资源,以服务器的路径为标准
(http
://localhost
:3306);需要加上项目名
http
://localhost
:3306/crud
-->
<script type
="text/javascript"
src
="${APP_PATH }/static/js/jquery-1.12.4.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
>
</div
>
</div
>
<div
class="form-group">
<label
class="col-sm-2 control-label">email
</label
>
<div
class="col-sm-10">
<input type
="text" name
="email" class="form-control" id
="email_update_input" placeholder
="email@qq.com">
<span
class="help-block"></span
>
</div
>
</div
>
<div
class="form-group">
<label
class="col-sm-2 control-label">gender
</label
>
<div
class="col-sm-10">
<label
class="radio-inline">
<input type
="radio" name
="gender" id
="gender1_update_input" value
="M" checked
="checked"> 男
</label
>
<label
class="radio-inline">
<input type
="radio" name
="gender" id
="gender2_update_input" value
="F"> 女
</label
>
</div
>
</div
>
<div
class="form-group">
<label
class="col-sm-2 control-label">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@qq.com">
<span
class="help-block"></span
>
</div
>
</div
>
<div
class="form-group">
<label
class="col-sm-2 control-label">gender
</label
>
<div
class="col-sm-10">
<label
class="radio-inline">
<input type
="radio" name
="gender" id
="gender1_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
>
<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
;
$
(function(){
to_page(1);
});
function
to_page(pn
){
$
.ajax({
url
:"${APP_PATH}/emps",
data
:"pn="+pn
,
type
:"GET",
success
:function(result
){
build_emps_table(result
);
build_page_info(result
);
build_page_nav(result
);
}
});
}
function
build_emps_table(result
){
$
("#emps_table tbody").empty();
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("编辑");
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("删除");
delBtn
.attr("del-id",item
.empId
);
var btnTd
= $
("<td></td>").append(editBtn
).append(" ").append(delBtn
);
$
("<tr></tr>").append(checkBoxTd
)
.append(empIdTd
)
.append(empNameTd
)
.append(genderTd
)
.append(emailTd
)
.append(deptNameTd
)
.append(btnTd
)
.appendTo("#emps_table tbody");
});
}
function
build_page_info(result
){
$
("#page_info_area").empty();
$
("#page_info_area").append("当前"+result
.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 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
);
$
.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
);
var navEle
= $
("<nav></nav>").append(ul
);
navEle
.appendTo("#page_nav_area");
}
function
reset_form(ele
){
$
(ele
)[0].reset();
$
(ele
).find("*").removeClass("has-error has-success");
$
(ele
).find(".help-block").text("");
}
$
("#emp_add_modal_btn").click(function(){
reset_form("#empAddModal form");
getDepts("#empAddModal select");
$
("#empAddModal").modal({
backdrop
:"static"
});
});
function
getDepts(ele
){
$
(ele
).empty();
$
.ajax({
url
:"${APP_PATH}/depts",
type
:"GET",
success
:function(result
){
$
.each(result
.extend
.depts
,function(){
var optionEle
= $
("<option></option>").append(this.deptName
).attr("value",this.deptId
);
optionEle
.appendTo(ele
);
});
}
});
}
function
validate_add_form(){
var empName
= $
("#empName_add_input").val();
var regName
= /(^[a
-zA
-Z0
-9_
-]{6,16}$
)|(^[\u2E80
-\u9FFF
]{2,5})/;
if(!regName
.test(empName
)){
show_validate_msg("#empName_add_input", "error", "用户名可以是2-5位中文或者6-16位英文和数字的组合");
return false;
}else{
show_validate_msg("#empName_add_input", "success", "");
};
var email
= $
("#email_add_input").val();
var regEmail
= /^([a
-z0
-9_\
.-
]+)@
([\da
-z\
.-
]+)\
.([a
-z\
.]{2,6})$
/;
if(!regEmail
.test(email
)){
show_validate_msg("#email_add_input", "error", "邮箱格式不正确");
return false;
}else{
show_validate_msg("#email_add_input", "success", "");
}
return true;
}
function
show_validate_msg(ele
,status
,msg
){
$
(ele
).parent().removeClass("has-success has-error");
$
(ele
).next("span").text("");
if("success"==status
){
$
(ele
).parent().addClass("has-success");
$
(ele
).next("span").text(msg
);
}else if("error" == status
){
$
(ele
).parent().addClass("has-error");
$
(ele
).next("span").text(msg
);
}
}
$
("#empName_add_input").change(function(){
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(){
if(!validate_add_form()){
return false;
};
if($
(this).attr("ajax-va")=="error"){
return false;
}
$
.ajax({
url
:"${APP_PATH}/emp",
type
:"POST",
data
:$
("#empAddModal form").serialize(),
success
:function(result
){
if(result
.code
== 100){
$
("#empAddModal").modal('hide');
to_page(totalRecord
);
}else{
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
);
}
}
}
});
});
$
(document
).on("click",".edit_btn",function(){
getDepts("#empUpdateModal select");
getEmp($
(this).attr("edit-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
){
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(){
var email
= $
("#email_update_input").val();
var regEmail
= /^([a
-z0
-9_\
.-
]+)@
([\da
-z\
.-
]+)\
.([a
-z\
.]{2,6})$
/;
if(!regEmail
.test(email
)){
show_validate_msg("#email_update_input", "error", "邮箱格式不正确");
return false;
}else{
show_validate_msg("#email_update_input", "success", "");
}
$
.ajax({
url
:"${APP_PATH}/emp/"+$
(this).attr("edit-id"),
type
:"PUT",
data
:$
("#empUpdateModal form").serialize(),
success
:function(result
){
$
("#empUpdateModal").modal("hide");
to_page(currentPage
);
}
});
});
$
(document
).on("click",".delete_btn",function(){
var empName
= $
(this).parents("tr").find("td:eq(2)").text();
var empId
= $
(this).attr("del-id");
if(confirm("确认删除【"+empName
+"】吗?")){
$
.ajax({
url
:"${APP_PATH}/emp/"+empId
,
type
:"DELETE",
success
:function(result
){
alert(result
.msg
);
to_page(currentPage
);
}
});
}
});
$
("#check_all").click(function(){
$
(".check_item").prop("checked",$
(this).prop("checked"));
});
$
(document
).on("click",".check_item",function(){
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(){
empNames
+= $
(this).parents("tr").find("td:eq(2)").text()+",";
del_idstr
+= $
(this).parents("tr").find("td:eq(1)").text()+"-";
});
empNames
= empNames
.substring(0, empNames
.length
-1);
del_idstr
= del_idstr
.substring(0, del_idstr
.length
-1);
if(confirm("确认删除【"+empNames
+"】吗?")){
$
.ajax({
url
:"${APP_PATH}/emp/"+del_idstr
,
type
:"DELETE",
success
:function(result
){
alert(result
.msg
);
to_page(currentPage
);
}
});
}
});
</script
>
</body
>
</html
>
index-2.jsp
<%@ 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
>
引入jquery
<script type
="text/javascript" src
="static/js/jquery-1.12.4.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
class="btn btn-success">按钮
</button
>
</body
>
</html
> -->
资源打包下载:https://download.csdn.net/download/weixin_43664418/11946604