使用Maven构建SSM加CRUD功能
项目结构
1. 创建Maven项目,并在pom.xml导入依赖
2. 编写web.xml文件
3. 编写Spring的配置文件(我这里叫applicationContext.xml)
引入命名空间 aop,beans,context,tx,
5. 编写SpringMVC的配置文件(我这里叫springmvc.xml)
引入命名空间 beans,context,mvc,
6. 编写mybatis配置文件(我这里叫mybatis-config.xml)
7. 编写数据库的配置信息(我用的是c3p0)c3p0.properties
8. 创建数据库
9. 使用mybatis逆向工程,根据数据库生成实体类
1.要使用这个先导入依赖
2.在项目下创建xml文件(我这里叫mbg.xml)
3在项目下创建xml文件(我这里叫mbg.xml)
4.编写一个Test运行写好的mybatis逆向工程(这个不用理解,直接复制粘贴就好)
5.运行完成就会生成对应的实体类,mapper.xml,和接口。
6.这个是逆向工程生成的mapper解释 https://www.cnblogs.com/luckypo/p/7356278.html
10. 使用 Bootstrap构建CRUD页面
导入Bootstrap的压缩文件,引入jquery压缩文件
Bootstrap下载:https://v3.bootcss.com/getting-started/#download
Bootstrap的使用说明:https://v3.bootcss.com/css/
11. 创建jsp文件 在里面引用bootstrap
12. 写一个通用的JSON返回类
13. controller类
1.DepartmentController.java
2.EmployeeController.java
14. Service类
1.DepartmentService.java
2.EmployeeService.java
到此SSM-CRUD就全部完成了,代码很多,对于有一定基础的人来说,这些代码可以给你提供一个新的写法,一些新的技巧
谢谢
需要源码的话可以联系我
项目结构
1. 创建Maven项目,并在pom.xml导入依赖
< properties>
< spring.version> 4.3.9.RELEASE spring.version>
< mybatis.version> 3.4.1 mybatis.version>
< slf4j.version> 1.7.7 slf4j.version>
< log4j.version> 1.2.17 log4j.version>
properties>
< dependencies>
< dependency>
< groupId> com.github.pagehelper groupId>
< artifactId> pagehelper artifactId>
< version> 5.0.0 version>
dependency>
< dependency>
< groupId> com.mchange groupId>
< artifactId> mchange-commons-java artifactId>
< version> 0.2.12 version>
dependency>
< dependency>
< groupId> org.springframework groupId>
< artifactId> spring-aspects artifactId>
< version> 4.3.9.RELEASE version>
dependency>
< dependency>
< groupId> junit groupId>
< artifactId> junit artifactId>
< version> 4.12 version>
< scope> test scope>
dependency>
< dependency>
< groupId> c3p0 groupId>
< artifactId> c3p0 artifactId>
< version> 0.9.1.2 version>
dependency>
< dependency>
< groupId> org.mybatis.generator groupId>
< artifactId> mybatis-generator-core artifactId>
< version> 1.3.5 version>
dependency>
< dependency>
< groupId> org.hibernate groupId>
< artifactId> hibernate-validator artifactId>
< version> 5.4.1.Final version>
dependency>
< dependency>
< groupId> org.springframework groupId>
< artifactId> spring-core artifactId>
< version> ${spring.version} version>
dependency>
< dependency>
< groupId> org.springframework groupId>
< artifactId> spring-web artifactId>
< version> ${spring.version} version>
dependency>
< dependency>
< groupId> org.springframework groupId>
< artifactId> spring-oxm artifactId>
< version> ${spring.version} version>
dependency>
< dependency>
< groupId> org.springframework groupId>
< artifactId> spring-tx artifactId>
< version> ${spring.version} version>
dependency>
< dependency>
< groupId> org.springframework groupId>
< artifactId> spring-jdbc artifactId>
< version> ${spring.version} version>
dependency>
< dependency>
< groupId> org.springframework groupId>
< artifactId> spring-webmvc artifactId>
< version> ${spring.version} version>
dependency>
< dependency>
< groupId> org.springframework groupId>
< artifactId> spring-aop artifactId>
< version> ${spring.version} version>
dependency>
< dependency>
< groupId> org.springframework groupId>
< artifactId> spring-context-support artifactId>
< version> ${spring.version} version>
dependency>
< dependency>
< groupId> org.springframework groupId>
< artifactId> spring-test artifactId>
< version> ${spring.version} version>
dependency>
< dependency>
< groupId> org.mybatis groupId>
< artifactId> mybatis artifactId>
< version> ${mybatis.version} version>
dependency>
< dependency>
< groupId> org.mybatis groupId>
< artifactId> mybatis-spring artifactId>
< version> 1.3.1 version>
dependency>
< dependency>
< groupId> javax groupId>
< artifactId> javaee-api artifactId>
< version> 7.0 version>
dependency>
< dependency>
< groupId> javax.servlet groupId>
< artifactId> javax.servlet-api artifactId>
< version> 4.0.0 version>
< scope> provided scope>
dependency>
< dependency>
< groupId> mysql groupId>
< artifactId> mysql-connector-java artifactId>
< version> 5.1.30 version>
dependency>
< dependency>
< groupId> commons-dbcp groupId>
< artifactId> commons-dbcp artifactId>
< version> 1.2.2 version>
dependency>
< dependency>
< groupId> jstl groupId>
< artifactId> jstl artifactId>
< version> 1.2 version>
dependency>
< dependency>
< groupId> log4j groupId>
< artifactId> log4j artifactId>
< version> ${log4j.version} version>
dependency>
< dependency>
< groupId> com.alibaba groupId>
< artifactId> fastjson artifactId>
< version> 1.1.41 version>
dependency>
< dependency>
< groupId> org.slf4j groupId>
< artifactId> slf4j-api artifactId>
< version> ${slf4j.version} version>
dependency>
< dependency>
< groupId> org.slf4j groupId>
< artifactId> slf4j-log4j12 artifactId>
< version> ${slf4j.version} version>
dependency>
< dependency>
< groupId> com.fasterxml.jackson.core groupId>
< artifactId> jackson-databind artifactId>
< version> 2.8.8 version>
dependency>
< dependency>
< groupId> org.codehaus.jackson groupId>
< artifactId> jackson-mapper-asl artifactId>
< version> 1.9.13 version>
dependency>
< dependency>
< groupId> commons-fileupload groupId>
< artifactId> commons-fileupload artifactId>
< version> 1.3.1 version>
dependency>
< dependency>
< groupId> commons-io groupId>
< artifactId> commons-io artifactId>
< version> 2.4 version>
dependency>
< dependency>
< groupId> commons-codec groupId>
< artifactId> commons-codec artifactId>
< version> 1.9 version>
dependency>
dependencies>
2. 编写web.xml文件
< 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>
< 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:springmvc.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>
< filter>
< filter-name> CharacterEncodingFilter filter-name>
< filter-class> org.springframework.web.filter.CharacterEncodingFilter filter-class>
< init-param>
< param-name> encoding param-name>
< param-value> utf-8 param-value>
init-param>
< init-param>
< param-name> forceRequestEncoding param-name>
< param-value> true param-value>
init-param>
< init-param>
< param-name> forceResponseEncoding param-name>
< param-value> true param-value>
init-param>
filter>
< filter-mapping>
< filter-name> CharacterEncodingFilter filter-name>
< url-pattern> /* url-pattern>
filter-mapping>
< filter>
< filter-name> HiddenHttpMethodFilter filter-name>
< filter-class> org.springframework.web.filter.HiddenHttpMethodFilter filter-class>
filter>
< filter-mapping>
< filter-name> HiddenHttpMethodFilter filter-name>
< url-pattern> /* url-pattern>
filter-mapping>
< filter>
< filter-name> HttpPutFormContentFilter filter-name>
< filter-class> org.springframework.web.filter.HttpPutFormContentFilter filter-class>
filter>
< filter-mapping>
< filter-name> HttpPutFormContentFilter filter-name>
< url-pattern> /* url-pattern>
filter-mapping>
3. 编写Spring的配置文件(我这里叫applicationContext.xml)
引入命名空间 aop,beans,context,tx,
< context: component-scan base-package = " com.ns" >
< context: exclude-filter type = " annotation"
expression = " org.springframework.stereotype.Controller" />
context: component-scan>
< context: property-placeholder location = " classpath:c3p0.properties" />
< bean id = " dataSource" class = " com.mchange.v2.c3p0.ComboPooledDataSource" >
< property name = " driverClass" value = " ${jdbc.driver}" > property>
< property name = " jdbcUrl" value = " ${jdbc.url}" > property>
< property name = " user" value = " ${jdbc.username}" > property>
< property name = " password" value = " ${jdbc.password}" > property>
bean>
< bean id = " sqlSessionFactory" class = " org.mybatis.spring.SqlSessionFactoryBean" >
< property name = " configLocation" value = " classpath:mybatis-config.xml" > property>
< property name = " dataSource" ref = " dataSource" > property>
< property name = " mapperLocations" value = " classpath:mapper/*.xml" > property>
bean>
< bean class = " org.mybatis.spring.mapper.MapperScannerConfigurer" >
< property name = " basePackage" value = " com.ns.dao" > property>
bean>
< 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 = " dataSource" > property>
bean>
< tx: annotation-driven transaction-manager = " transactionManager" />
< aop: config>
< aop: pointcut expression = " execution(* com.ns.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 = " *" />
< tx: method name = " get*" read-only = " true" />
tx: attributes>
tx: advice>
5. 编写SpringMVC的配置文件(我这里叫springmvc.xml)
引入命名空间 beans,context,mvc,
< context: component-scan base-package = " com.ns" use-default-filters = " false" >
< context: include-filter type = " annotation" expression = " org.springframework.stereotype.Controller" />
< context: exclude-filter type = " annotation"
expression = " org.springframework.stereotype.Service" />
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>
< mvc: default-servlet-handler/>
< mvc: annotation-driven />
6. 编写mybatis配置文件(我这里叫mybatis-config.xml)
< configuration>
< settings>
< setting name = " mapUnderscoreToCamelCase" value = " true" />
settings>
< typeAliases>
< package name = " com.ns.pojo" />
typeAliases>
< plugins>
< plugin interceptor = " com.github.pagehelper.PageInterceptor" >
< property name = " reasonable" value = " true" />
plugin>
plugins>
configuration>
7. 编写数据库的配置信息(我用的是c3p0)c3p0.properties
jdbc.url=jdbc:mysql://localhost:3306/ssm_curd
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
8. 创建数据库
9. 使用mybatis逆向工程,根据数据库生成实体类
1.要使用这个先导入依赖
org.mybatis.generator
mybatis-generator-core
1.3.5
2.在项目下创建xml文件(我这里叫mbg.xml)
3在项目下创建xml文件(我这里叫mbg.xml)
< 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_curd" userId = " root"
password = " root" >
jdbcConnection>
< javaTypeResolver>
< property name = " forceBigDecimals" value = " false" />
javaTypeResolver>
< javaModelGenerator targetPackage = " com.ns.pojo"
targetProject = " .\src\main\java" >
< property name = " enableSubPackages" value = " true" />
< property name = " trimStrings" value = " true" />
javaModelGenerator>
< sqlMapGenerator targetPackage = " mapper" targetProject = " .\src\main\resources" >
< property name = " enableSubPackages" value = " true" />
sqlMapGenerator>
< javaClientGenerator type = " XMLMAPPER"
targetPackage = " com.ns.dao" targetProject = " .\src\main\java" >
< property name = " enableSubPackages" value = " true" />
javaClientGenerator>
< table tableName = " tnl_position" domainObjectName = " Position" > table>
context>
generatorConfiguration>
4.编写一个Test运行写好的mybatis逆向工程(这个不用理解,直接复制粘贴就好)
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) ;
}
}
5.运行完成就会生成对应的实体类,mapper.xml,和接口。
6.这个是逆向工程生成的mapper解释 https://www.cnblogs.com/luckypo/p/7356278.html
10. 使用 Bootstrap构建CRUD页面
导入Bootstrap的压缩文件,引入jquery压缩文件
Bootstrap下载:https://v3.bootcss.com/getting-started/#download
Bootstrap的使用说明:https://v3.bootcss.com/css/
11. 创建jsp文件 在里面引用bootstrap
我使用了Ajax做CRUD
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
< html>
< head>
< meta http-equiv = " Content-Type" content = " text/html; charset=UTF-8" >
< title> 员工列表 title>
<%
pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
< script type = " text/javascript" src = " ${pageContext.request.contextPath }/static/js/jquery-1.10.2.min.js" > script>
< link href = " ${pageContext.request.contextPath }/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel = " stylesheet" >
< script src = " ${pageContext.request.contextPath }/static/bootstrap-3.3.7-dist/js/bootstrap.min.js" > script>
head>
< body>
< div class = " modal fade" id = " empUpdateModal" tabindex = " -1" role = " dialog" aria-labelledby = " myModalLabel" >
< div class = " modal-dialog" role = " document" >
< div class = " modal-content" >
< div class = " modal-header" >
< button type = " button" class = " close" data-dismiss = " modal" aria-label = " Close" > < span aria-hidden = " true" > × span> button>
< h4 class = " modal-title" > 员工修改 h4>
div>
< div class = " modal-body" >
< form class = " form-horizontal" >
< div class = " form-group" >
< label class = " col-sm-2 control-label" > empName label>
< div class = " col-sm-10" >
< p class = " form-control-static" id = " empName_update_static" > p>
< span class = " help-block" > span>
div>
div>
< div class = " form-group" >
< label class = " col-sm-2 control-label" > email label>
< div class = " col-sm-10" >
< input type = " text" name = " email" class = " form-control" id = " email_update_input"
placeholder = " [email protected] " >
< 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 = " G" > 女
label>
div>
div>
< div class = " form-group" >
< label class = " col-sm-2 control-label" > deptName label>
< div class = " col-sm-4" >
< select class = " form-control" name = " dId" id = " dept_update_select" >
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 protected] " >
< 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 = " G" > 女
label>
div>
div>
< div class = " form-group" >
< label class = " col-sm-2 control-label" > deptName label>
< div class = " col-sm-4" >
< select class = " form-control" name = " dId" id = " dept_add_select" >
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_model_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> emial 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;
var 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_emps_info ( result) ;
build_emps_nav ( result) ;
}
} ) ;
}
function build_emps_table ( result) {
$ ( "#emps_table tbody" ) . empty ( ) ;
var emps= result. extend. pageInfo. list;
$. each ( emps, function ( index, item) {
var checkBoxTd= $ ( " ")
var empIdTd= $ ( " ") . append ( item. empId) ;
var empNameTd= $ ( " ") . append ( item. empName) ;
var genderTd= $ ( " ") . append ( item. gender== 'M' ? "男" : "女" ) ;
var emailTd= $ ( " ") . append ( item. email) ;
var deptNameTd= $ ( " ") . append ( item. department. deptName) ;
var editBtn= $ ( " " ) . addClass ( "btn btn-primary btn-sm edit_btn" )
. append ( $ ( " " ) . addClass ( "glyphicon glyphicon-pencil" ) )
. append ( "编辑" ) ;
editBtn. attr ( "edit-id" , item. empId) ;
var delBtn= $ ( " " ) . addClass ( "btn btn-danger btn-sm delete_btn" )
. append ( $ ( " " ) . addClass ( "glyphicon glyphicon-trash" ) )
. append ( "删除" ) ;
delBtn. attr ( "delete-id" , item. empId) ;
var btnTd= $ ( " ") . append ( editBtn) . append ( "" ) . append ( delBtn) ;
$ ( " " ) . append ( checkBoxTd)
. append ( empIdTd)
. append ( empNameTd)
. append ( genderTd)
. append ( emailTd)
. append ( deptNameTd)
. append ( btnTd)
. appendTo ( "#emps_table tbody" ) ;
} ) ;
}
function build_emps_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_emps_nav ( result) {
$ ( "#page_nav_area" ) . empty ( ) ;
var ul= $ ( "" ) . addClass ( "pagination" ) ;
var firstPageLi= $ ( " " ) . append ( $ ( " " ) . append ( "首页" ) . attr ( "href" , "#" ) ) ;
var prePageLi= $ ( " " ) . append ( $ ( " " ) . 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= $ ( " " ) . append ( $ ( " " ) . append ( "»" ) ) ;
var lasePageLi= $ ( " " ) . append ( $ ( " " ) . append ( "末页" ) . attr ( "href" , "#" ) ) ;
if ( result. extend. pageInfo. hasNextPage == false ) {
nextPageLi. addClass ( "disabled" ) ;
lasePageLi. addClass ( "disabled" ) ;
} else {
nextPageLi. click ( function ( ) {
to_page ( result. extend. pageInfo. pageNum+ 1 ) ;
} )
lasePageLi. click ( function ( ) {
to_page ( result. extend. pageInfo. pages) ;
} )
}
ul. append ( firstPageLi)
. append ( prePageLi)
$. each ( result. extend. pageInfo. navigatepageNums, function ( index, item) {
var numLi= $ ( " " ) . append ( $ ( " " ) . append ( item) ) ;
if ( result. extend. pageInfo. pageNum == item) {
numLi. addClass ( "active" ) ;
}
numLi. click ( function ( ) {
to_page ( item) ;
} ) ;
ul. append ( numLi) ;
} ) ;
ul. append ( nextPageLi) . append ( lasePageLi) ;
var navEle= $ ( " " ) . append ( ul) ;
navEle. appendTo ( "#page_nav_area" ) ;
}
function reset_form ( ele) {
$ ( ele) [ 0 ] . reset ( ) ;
$ ( ele) . find ( "*" ) . removeClass ( "has-error has-success" )
$ ( ele) . find ( ".help-block" ) . text ( "" ) ;
}
$ ( "#emp_add_model_btn" ) . click ( function ( ) {
reset_form ( "#empAddModal form" ) ;
getDepts ( "#dept_add_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 ( index, item) {
var optionEle= $ ( " " ) . append ( item. deptName) . attr ( "value" , item. deptId) ;
optionEle. appendTo ( ele) ;
} ) ;
}
} ) ;
}
function validate_add_form ( ) {
var empName= $ ( "#empName_add_input" ) . val ( ) ;
var regName= /(^[a-zA-Z0-9_-]{4,16}$)|(^[\u2E80-\u9FFF]{2,5})/ ;
if ( ! regName. test ( empName) ) {
show_validate_msg ( "#empName_add_input" , "error" , "用户名可以是2-5为中文" ) ;
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 ( $ ( "#emp_save_btn" ) . 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" ) ;
lookEmp ( $ ( this ) . attr ( "edit-id" ) ) ;
$ ( "#emp_update_btn" ) . attr ( "edit-id" , $ ( this ) . attr ( "edit-id" ) ) ;
$ ( "#empUpdateModal" ) . modal ( {
backdrop: "static"
} ) ;
} ) ;
function lookEmp ( 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 ( reuslt) {
$ ( "#empUpdateModal" ) . modal ( "hide" ) ;
to_page ( currentPage) ;
}
} )
} )
$ ( document) . on ( "click" , ".delete_btn" , function ( ) {
var empName= $ ( this ) . parents ( "tr" ) . find ( "td:eq(2)" ) . text ( ) ;
if ( confirm ( "确认删除员工【" + empName+ "】吗?" ) ) {
$. ajax ( {
url: "${APP_PATH}/emp/" + $ ( this ) . attr ( "delete-id" ) ,
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>
12. 写一个通用的JSON返回类
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;
}
}
13. controller类
1.DepartmentController.java
@Controller
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
@RequestMapping ( "/depts" )
@ResponseBody
public Msg AllDepts ( ) {
List< Department> list= departmentService. AllDepts ( ) ;
return Msg. success ( ) . add ( "depts" , list) ;
}
}
2.EmployeeController.java
@Controller
public class EmployeeController {
@Autowired
EmployeeService EmployeeService;
@RequestMapping ( value= "/emp/{ids}" , method= RequestMethod. DELETE)
@ResponseBody
public Msg deleteEmpBy ( @PathVariable ( "ids" ) String ids) {
if ( ids. contains ( "-" ) ) {
List< Integer> del_id= new ArrayList < Integer> ( ) ;
String[ ] str_ids = ids. split ( "-" ) ;
for ( String string : str_ids) {
del_id. add ( Integer. parseInt ( string) ) ;
}
EmployeeService. deleteBatch ( del_id) ;
} else {
Integer id= Integer. parseInt ( ids) ;
EmployeeService. deleteEmpById ( id) ;
}
return Msg. success ( ) ;
}
@RequestMapping ( value= "/emp/{empId}" , method= RequestMethod. PUT)
@ResponseBody
public Msg saveEmp ( Employee employee) {
EmployeeService. updateEmp ( employee) ;
return Msg. success ( ) ;
}
@RequestMapping ( value= "/emp/{id}" , method= RequestMethod. GET)
@ResponseBody
public Msg lookEmp ( @PathVariable ( "id" ) Integer id) {
Employee employee= EmployeeService. lookEmp ( id) ;
return Msg. success ( ) . add ( "emp" , employee) ;
}
@RequestMapping ( "/checkuser" )
@ResponseBody
public Msg checkuser ( @RequestParam ( "empName" ) String empName) {
String regx= "(^[a-zA-Z0-9_-]{4,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 < String, Object> ( ) ;
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 findEmpsWithJSON (
@RequestParam ( value= "pn" , defaultValue= "1" ) Integer pn
) {
PageHelper. startPage ( pn, 5 ) ;
List< Employee> emps= EmployeeService. getAll ( ) ;
PageInfo page = new PageInfo ( emps, 5 ) ;
return Msg. success ( ) . add ( "pageInfo" , page) ;
}
public String findEmps ( @RequestParam ( value= "pn" , defaultValue= "1" ) Integer pn
, Model model) {
PageHelper. startPage ( pn, 5 ) ;
List< Employee> emps= EmployeeService. getAll ( ) ;
PageInfo page = new PageInfo ( emps, 5 ) ;
model. addAttribute ( "pageInfo" , page) ;
return "list" ;
}
}
14. Service类
1.DepartmentService.java
@Service
public class DepartmentService {
@Autowired
private DepartmentMapper departmentMapper;
public List< Department> AllDepts ( ) {
List< Department> list = departmentMapper. selectByExample ( null) ;
return list;
}
}
2.EmployeeService.java
@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 lookEmp ( Integer id) {
Employee employee = employeeMapper. selectByPrimaryKey ( id) ;
return employee;
}
public void updateEmp ( Employee employee) {
employeeMapper. updateByPrimaryKeySelective ( employee) ;
}
public void deleteEmpById ( 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) ;
}
}
到此SSM-CRUD就全部完成了,代码很多,对于有一定基础的人来说,这些代码可以给你提供一个新的写法,一些新的技巧
谢谢
需要源码的话可以联系我