SSM高级整合项目即采用Spring、SpringMVC和MyBatis框架实现增删改查操作,主要功能点包括分页、数据校验(jQuery前端校验和JSR303后端校验)、AJAX请求及REST风格的URI等。
SSM高级整合项目的技术点包括:
- 基础框架-SSM(Spring + SpringMVC + MyBatis)
- 项目依赖管理Maven
- 数据库-MySQL
- 前端框架-Bootstrap,可快速搭建简洁美观的界面
- 分页-PageHelper
- 逆向工程-MyBatis Generator
以下主要介绍SSM高级整合项目的第一步操作——基础环境搭建,包括
- 创建一个Maven工程
- 引入项目所依赖的jar包
- 引入Bootstrap前端框架
- 编写SSM整合的关键配置文件
- 测试Mapper
项目完整实现代码下载地址:https://download.csdn.net/download/bingbeichen/10578683。
###1. 创建Maven工程
第一步,安装Maven核心程序。
- 解压Maven核心程序的压缩包,将其存放在一个非中文且无空格的目录下,如D:\iBaBei\Java
- 配置Maven相关的环境变量
- 配置MAVEN_HOME或M2_HOME为D:\iBaBei\Java\apache-maven-3.2.2
- 在path环境变量中添加D:\iBaBei\Java\apache-maven-3.2.2\bin
- 验证,即在WINDOWS命令行中执行mvn -v命令查看Maven版本。
第二步,修改Maven本地仓库的默认位置。
- 本地仓库的默认位置为C:\Users[当前用户名].m2\repository
- 在Maven解压目录的conf\setting.xml中找到localRepository标签
- 将
<localRepository>/path/to/local/repo</localRepository>
从注释中释放 - 将标签体内容修改为自定义的本地仓库位置。
第三步,在Eclipse中设置Maven插件。
- Window — Preferences — Maven — Installations — Add
- 将Installation home配置为Maven核心程序所在位置
- 将Installation name配置为apache-maven-3.2.2
- Window — Preferences — Maven — User Settings
- 将User Settings配置为apache-maven-3.2.2\conf\setting.xml文件所在位置
第四步,在Eclipse中创建一个Maven的Web工程。
- New — Maven Project — 勾选Create a simple project — Next
- 配置工程的坐标(Group Id、Artifact Id、Version)
- 配置工程的打包方式为war(若为Java工程则选择jar)
- Properties — Project Facets — 取消勾选Dynamic Web Module — Apply,以欺骗Eclipse该工程为Java工程
- 再勾选Dynamic Web Module — Further configuration available — 配置Content directory为src/main/webapp — 勾选Generate web.xml deployment descriptor,以产生META-INF和WEB-INF目录。
至此,Maven工程创建完毕。
###2. 在pom.xml文件中引入项目所依赖的jar包
<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.qiaobc</groupId>
<artifactId>ssm-crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<!--
引入项目所依赖的jar包:
spring(切面编程、事务管理)、springmvc、mybatis、
数据库连接池c3p0及mysql驱动包
以及其他常用包(jstl、servlet-api、junit等)
-->
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</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>
</project>
至此,项目基础环境搭建所需要的jar包全部导入完毕,后续用到其他包再依次导入。
###3. 引入Bootstrap前端框架
下载Bootstrap,解压后存放在项目的src/main/webapp/static目录下。
下载jQuery,存放在项目的src/main/webapp/static/javascript目录下。
如需引入Bootstrap前端框架,仅需要在JSP页面添加如下内容:
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- 引入jQuery -->
<script type="text/javascript" src="static/javascript/jquery-3.3.1.min.js"></script>
<!-- 引入Bootstrap的样式和JS文件 -->
<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>
至此,引入Bootstrap前端框架的操作完成,Bootstrap的具体使用请参看官方文档。
###4. 编写SSM整合的关键配置文件
在web.xml中配置启动Spring容器、配置SpringMVC的前端控制器、字符编码过滤器和REST风格的URI,具体如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- 1. 启动Spring容器 -->
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 2. 配置SpringMVC的前端控制器 -->
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<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>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 3. 配置SpringMVC的字符编码过滤器 : 一定要放在所有过滤器之前 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 4. 配置使用REST风格的URI : 将页面发送来的POST请求转化为对应的DELETE和PUT请求 -->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
编写SpringMVC的配置文件WEB-INF/dispatcherServlet-servlet.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/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">
<context:component-scan base-package="com.qiaobc.crud" use-default-filters="false">
<!-- 只扫描@Controller注解 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置处理静态资源请求:将SpringMVC不能处理的请求交给TOMCAT -->
<mvc:default-servlet-handler/>
<!-- 配置支持高级功能:JSR303校验、映射动态请求、快捷的AJAX请求等 -->
<mvc:annotation-driven/>
</beans>
编写Spring的配置文件src/main/resources/applicationContext.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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">
<!-- Spring配置文件:负责与业务逻辑有关的配置 -->
<context:component-scan base-package="com.qiaobc.crud">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:dbconfig.properties"/>
<!-- 1. 配置数据源 -->
<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>
<!-- 2. 配置与MyBatis框架的整合 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="pooledDataSource"></property>
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<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.qiaobc.crud.dao"></property>
</bean>
<!-- 3. 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="pooledDataSource"></property>
</bean>
<!-- 4. 基于XML配置的事务,也可开启基于注解的事务 -->
<aop:config>
<!-- 切入点表达式 -->
<aop:pointcut expression="execution(* com.qiaobc.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>
<!-- 事务管理器管理数据源,切入点配置即决定切入哪些方法,事务增强配置即决定切入后怎么办 -->
</beans>
其中,src/main/resources/dbconfig.properties文件内容如下:
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm-crud
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
编写MyBatis配置文件src/main/resources/mybatis-config.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 使用驼峰命名法 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
至此,SSM整合的web.xml、SpringMVC配置文件、Spring配置文件、MyBatis配置文件均编写完毕。
###5. MyBatis逆向工程
创建项目所需要的数据表:
CREATE TABLE tbl_department(
id INT(11) AUTO_INCREMENT PRIMARY KEY,
dept_name VARCHAR(255)
);
CREATE TABLE tbl_employee(
id INT(11) AUTO_INCREMENT PRIMARY KEY,
last_name VARCHAR(255),
gender CHAR(1),
email VARCHAR(255),
dept_id INT(11),
FOREIGN KEY(dept_id) REFERENCES tbl_department(id)
);
在项目的pom.xml文件中引入MyBatis Gnerator所需要的jar包:
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
参考MBG官方文档,在项目根目录下创建MBG所需要的配置文件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="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 配置JavaBean生成策略 -->
<javaModelGenerator
targetPackage="com.qiaobc.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>
<!-- 配置Mapper接口的生成策略 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.qiaobc.crud.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 指定逆向分析的数据表,根据数据表生成JavaBean -->
<table tableName="tbl_employee" domainObjectName="Employee"></table>
<table tableName="tbl_department" domainObjectName="Department"></table>
</context>
</generatorConfiguration>
使用Java代码运行MyBatis Generator,测试代码如下:
@Test
public void testRunMBG() 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);
}
至此,即可在对应的包中生成数据表所对应的JavaBean类、Mapper接口和SQL映射文件。
###6. 修改Mapper文件
由于MyBatis逆向工程所生成的Mapper文件中,员工查询方法没有同时返回其部门名信息,故需要添加带部门的员工查询方法。
在EmployeeMapper.java文件中添加如下两个方法:
// 注意:需要在Employee类中添加private Department dept属性
List<Employee> selectByExampleWithDept(EmployeeExample example);
Employee selectByPrimaryKeyWithDept(Integer id);
在mapper/EmployeeMapper.xml文件中添加方法所对应的SQL映射:
<resultMap id="WithDeptResultMap" type="com.qiaobc.crud.bean.Employee">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="last_name" jdbcType="VARCHAR" property="lastName" />
<result column="gender" jdbcType="CHAR" property="gender" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="dept_id" jdbcType="INTEGER" property="deptId" />
<association property="dept" javaType="com.qiaobc.crud.bean.Department">
<id column="id" property="id"/>
<result column="dept_name" property=""/>
</association>
</resultMap>
<sql id="WithDept_Column_List">
e.id, e.last_name, e.gender, e.email, e.dept_id, d.id, d.dept_name
</sql>
<!-- List<Employee> selectByExampleWithDept(EmployeeExample example); -->
<select id="selectByExampleWithDept" parameterType="com.qiaobc.crud.bean.EmployeeExample" resultMap="WithDeptResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="WithDept_Column_List" />
FROM tbl_employee e LEFT JOIN tbl_department d ON e.`dept_id`=d.`id`
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
<!-- Employee selectByPrimaryKeyWithDept(Integer id); -->
<select id="selectByPrimaryKeyWithDept" parameterType="java.lang.Integer" resultMap="WithDeptResultMap">
select
<include refid="WithDept_Column_List" />
from tbl_employee
where id = #{id,jdbcType=INTEGER}
</select>
###7. 搭建Spring单元测试环境
第一步,导入Spring单元测试所需要的jar包。
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.0.RELEASE</version>
<scope>test</scope>
</dependency>
第二步,在单元测试类上使用@ContextConfiguration注解指定Spring配置文件的位置,并使用@RunWith注解指定所使用的测试模块。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value= {"classpath:applicationContext.xml"})
第三步,直接使用@Autowired注解即可注入Mapper接口对象,进而进行增删改查操作。
测试代码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value= {"classpath:applicationContext.xml"})
public class MapperTest {
@Autowired
private DepartmentMapper deptMapper;
@Autowired
private EmployeeMapper empMapper;
@Autowired
private SqlSession sqlSession;
// 注意:需要在Department类中添加无参和有参的构造器
@Test
public void testDeptMapper() {
deptMapper.insertSelective(new Department(null, "开发部"));
deptMapper.insertSelective(new Department(null, "测试部"));
deptMapper.insertSelective(new Department(null, "人事部"));
deptMapper.insertSelective(new Department(null, "采购部"));
deptMapper.insertSelective(new Department(null, "销售部"));
}
@Test
public void testEmpMapper() {
empMapper.insertSelective(new Employee(null, "qiaobb", "M", "qiaobb@163.com", 1));
}
// 批量插入多个员工:使用可以执行批量操作的SqlSession对象
// 注意:需要在Employee类中添加无参和有参的构造器
@Test
public void testEmpMapperBatch() {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
for(int i = 0; i < 1000; i++) {
mapper.insertSelective(new Employee(null, "qiaobc" + i, "F", "qiaobc" + i + "@163.com", i % 5 + 1));
}
}
}