项目结构:
项目截图:
第一步:配置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>ssm-crud</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <!-- 引入项目依赖的jar包 --> <!-- 1.SpringMVC和Sping --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- 2.Spring-JDBC --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- Spring-test 单元测试--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.7.RELEASE</version> <scope>test</scope> </dependency> <!-- 3.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> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8.RELEASE</version> </dependency> <!-- 4.Mybatis --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <!-- 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> <!-- 5.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.2</version> </dependency> <!-- 配置c3p0必要的包 --> <!-- https://mvnrepository.com/artifact/com.mchange/mchange-commons-java --> <dependency> <groupId>com.mchange</groupId> <artifactId>mchange-commons-java</artifactId> <version>0.2.3.4</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.27</version> </dependency> <!-- 其他包 jstl servlet-api junit --> <!-- https://mvnrepository.com/artifact/jstl/jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- 引入分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency> </dependencies> <build/> </project>
第二步:配置Spring,SpringMVC以及Mybatis的配置文件
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <!--Spring的配置文件 :主要配置和逻辑业务有关的--> <!-- 扫描包 --> <context:component-scan base-package="com.ssm"> <!-- 不扫描@Controller注解 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 引入外部配置文件 --> <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.jdbcdriverClass}"></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.dao"></property> </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.ssm.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> <!--以get开头的所有方法--> <tx:method name="get*" read-only="true"></tx:method> </tx:attributes> </tx:advice> <!-- Spring配置文件的核心点:数据源,与mybatis的整合,事务控制 --> <!-- 配置一个可以批量的执行sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> <!-- 执行器类型,批量-batch --> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </bean> </beans>
给数据源配置的数据库配置文件dbconfig.properties
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm jdbc.jdbcdriverClass=com.mysql.jdbc.Driver jdbc.user=root jdbc.password=123
SpringMVC的配置文件dispatch-servlet.xml,本来这个文件应该在WEB-INF下的,在后面搭载上tomcat后报错找不到此文件,所以放到类路径下来了。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-mvc-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <!--SpringMVC的配置文件 :主要包含网站跳转的控制,配置--> <context:component-scan base-package="com.ssm" use-default-filters="false"> <!-- 扫描@Controller注解 不扫描用exclude --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 配置视图解析器 方便页面返回 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- spring中加入jstl标签库 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/views/"></property> <!-- 后缀 --> <property name="suffix" value=".jsp"></property> </bean> <!-- 两个标准配置 --> <!-- 将SpringMVC不能处理的请求交给tomcat --> <mvc:default-servlet-handler></mvc:default-servlet-handler> <!-- 能支持SpringMVC更高级的一些功能 JSR303的校验,快捷的ajax,映射动态请求--> <mvc:annotation-driven></mvc:annotation-driven> </beans>
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> <!-- 开启自动驼峰命名规则(camel case)映射, 即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。 --> <settings> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> <!-- 类型别名 自定义别名name为类所在的包路径--> <typeAliases> <package name="com.ssm.bean"></package> </typeAliases> <!-- 分页的配置 --> <plugins> <!-- com.github.pagehelper为PageHelper类所在包名 --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 --> <!-- <property name="param1" value="value1"/> --> </plugin> </plugins> </configuration>
第三步:配置一个mbg.xml文件与pom.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" userId="root" password="123"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 指定javabean生成的位置 --> <javaModelGenerator targetPackage="com.ssm.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.dao" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 指定每个表的 生成策略--> <table tableName="emp" domainObjectName="Employee" > </table> <table tableName="dept" domainObjectName="Department" > </table> </context> </generatorConfiguration>
第四步:建立一个MBGTest.java的文件运行后会自动生成bean,dao包下的文件,以及mapper下的xml文件
package com.ssm.test; import java.io.File; import java.io.IOException; import java.sql.SQLException; 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.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback; //自动生成了bean下的文件以及dao下的,还有mapper下的xml文件 public class MBGTest { public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException { 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); } }
第五步:因为是两个表的查询,所以需要在生成的文件中添加多表查询的功能。
DepartmentMapper.java中
//====================新定义的两个查询,多表联查======================== List<Employee> selectByExampleWithDept(EmployeeExample example); Employee selectByPrimaryKeyWithDept(Integer empId); //===========================================================
EmployeeMapper.xml
<!-- ===========新增多表查询============= --> <sql id="WithDept_Column_List"> e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name </sql> <resultMap id="WithDeptResultMap" type="com.ssm.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" /> <!-- 指定联合查询的部门字段的封装 --> <association property="department" javaType="com.ssm.bean.Department"> <id column="dept_id" jdbcType="INTEGER" property="deptId" /> <result column="dept_name" jdbcType="VARCHAR" property="deptName" /> </association> </resultMap> <!-- 带条件的多表查询 --> <select id="selectByExampleWithDept" resultMap="WithDeptResultMap"> select <if test="distinct"> distinct </if> <include refid="WithDept_Column_List" /> FROM emp e LEFT JOIN 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 emp e LEFT JOIN dept d ON e.d_id=d.dept_id where emp_id = #{empId,jdbcType=INTEGER} </select> <!-- =================================================== -->
EmployeeService.java
package com.ssm.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ssm.bean.Employee; import com.ssm.dao.EmployeeMapper; //业务逻辑组件 @Service public class EmployeeService { @Autowired//自动注入 EmployeeMapper employeeMapper; public List<Employee> getAll(){ return employeeMapper.selectByExampleWithDept(null); } }
EmployeeController.java
package com.ssm.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ssm.bean.Employee; import com.ssm.service.EmployeeService; //处理员工crud @Controller public class EmployeeController { @Autowired EmployeeService employeeService; @RequestMapping("/emps") // 默认值为第一页数据 public String getEmps( @RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) { // 引入PageHelper分页插件 // 在查询之前只需要调用 pn=第几页,5=每页多少条 PageHelper.startPage(pn, 3); // startPage后紧跟的查询就是一个分页查询 List<Employee> emps = employeeService.getAll(); // pageinfo包装查询后的结果,只需要pageinfo交给页面,封装了详细的信息 // 5=传入分页连续显示的页数 PageInfo page = new PageInfo(emps, 5); model.addAttribute("pageInfo", page); return "list"; } }
第六步:在index.jsp文件中添加
<jsp:forward page="/emps"></jsp:forward>
会通过控制器转到list.jsp页面
第七步:list.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>员工列表</title> <% //key=APP_PATH value=request.getContextPath()拿到当前项目路径 pageContext.setAttribute("APP_PATH", request.getContextPath()); %> <!-- web路径,不以/开始的相对路径找资源,以当前资源的路径为基准,经常容易出问题 以/开始的相对路径,找资源,以服务器的路径为标准(http://localhost:3306/ssm)需要加上项目名 --> <script type="text/javascript" src="${APP_PATH}/static/js/jquery-3.2.1.min.js"></script> <link rel="stylesheet" type="text/css" href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> <script type="text/javascript" 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>SSH-CURD</h1> </div> </div> <!-- 按钮 --> <div class="row"> <!-- 占4列,偏移8列 --> <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> <!-- 前一页是当前页-1 --> <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>