该篇博客使用idea 工具逐步完成 SSM框架的搭建。
一 、 新建项目
idea 创建项目可参照 :Spring MVC 基于HTML 教程 (二)进行项目的创建,此处不再赘述。
项目结构如下:
二、 搭建项目
1. 引入相关依赖,完整依赖如下:
<?xml version="1.0" encoding="UTF-8"?>
<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.dongl</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.1.5.RELEASE</spring.version>
<slf4j.version>1.7.25</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-context:Spring上下文 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-aop:aop依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- aspectjweaver:aop相关依赖 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!-- spring-tx:spring事务依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- servlet-api:servlet相关依赖,用于页面 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- jsp-api:servlet相关依赖,用于页面 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!--数据库依赖 start -->
<!-- spring-jdbc:jdbc模板依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mysql-connector-java:mysql连接驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- mybatis:mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis-spring:spring整合mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- c3p0:数据库连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!--数据库依赖 end -->
<!--log start -->
<!-- log4j:日志相关依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- slf4j-api:日志相关依赖 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- slf4j-log4j12:日志相关依赖 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--log end -->
<!-- com.alibaba.fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>ssm</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
2. 创建表结构,及相关的dao 和service层接口
2.1 创建user 表,表结构如下:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
2.2 定义实体类 User
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
}
get/set 方法自己生成。
2.3 定义dao和service相关接口
// dao 的实现类可以有mybatis的代理实现,项目中可不必实现
public interface UserDao {
public List<User> findAll();
public User findById(Integer id);
public int save(User user);
public int deleteById(Integer id);
}
service层接口
public interface UserService {
public List<User> findAll();
public User findById(Integer id);
public int save(User user);
public int deleteById(Integer id);
}
service层实现类:
@Service("userService")
public class UserServiceImpl implements UserService {
@Override
public List<User> findAll() {
return null;
}
@Override
public User findById(Integer id) {
return null;
}
@Override
public int save(User user) {
return 0;
}
@Override
public int deleteById(Integer id) {
return 0;
}
}
2.4 通过spring 配置管理dao和service接口
以上dao和service 接口只有放入到容器中才能实现注解方式,因此创建spring配置文件,applicationcontext.xml 文件。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!--开启注解扫描 ,spring配置文件只处理service和dao层,Controller层由springmvc.xml扫描 -->
<context:component-scan base-package="com.dongl">
<!--配置哪些注解不扫描 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
配置好 applicationcontext.xml 文件后,即可在 UserServiceImpl.java 类上使用 @Service("userService") 注解。
三、前端和Springmvc 的整合
3.1 在 web.xml 文件中配置前端控制器,springmvc.xml等,完整配置如下:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<!--解决中文乱码的过滤器 -->
<filter>
<filter-name>encodingFilter</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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--整合springmvc-->
<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>
<!-- 因为tomcat的默认启动资源文件是index.jsp,修改默认启动首页-->
<welcome-file-list>
<welcome-file>login.html</welcome-file>
<welcome-file>login.htm</welcome-file>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
3.2 配置 springmvc.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1. 开启注解扫描,只扫描Controller注解-->
<context:component-scan base-package="com.dongl">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 2. 配置视图解析器对象 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--把页面及静态资源放到 WEB-INF 外 -->
<property name="prefix" value="/statics/views/"/>
<!--把页面及静态资源放到 WEB-INF 中 -->
<!--<property name="prefix" value="/WEB-INF/pages/"/>-->
<property name="suffix" value=".html"/>
</bean>
<!-- 3. 过滤静态资源,向 DispatcherServlet 声明静态文件 不拦截 -->
<mvc:resources location="/statics/css/" mapping="/statics/css/**"/>
<mvc:resources location="/statics/images/" mapping="/statics/images/**"/>
<mvc:resources location="/statics/js/" mapping="/statics/js/**"/>
<!-- 4. 静态资源的请求,就将该请求转由Web应用服务器默认的Servlet处理 ,该配置可以运行HTML脚本文件-->
<mvc:default-servlet-handler/>
<!-- 5. 开启springmvc注解支持 -->
<mvc:annotation-driven/>
<!--6. 用于把后端数据以JSON格式展示到浏览器 支持fastjson.jar -->
</beans>
3.3 创建 对应的目录,目录结构如下:
四、Spring整合Springmvc
在Spring整合Springmvc 时,需要服务启动时 加载 applicationContext.xml 文件,用于将Spring实例交给容器管理。这时可以使用监听器进行 applicationContext.xml 的初始化。因此需要在 web.xml 中配置监听器,配置如下:
<!--配置监听器用于把实例交给spring容器管理-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
由于该监听器默认 加载WEB-INF 目录下的 applicationContext.xml 文件,因此需要指定 applicationContext.xml 文件所在路径。
<!--设置配置文件的路径,-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
通过以上配置,即可在控制类中使用:@Autowired 注入实体。
web.xml 的完整配置,如下:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<!--解决中文乱码的过滤器 -->
<filter>
<filter-name>encodingFilter</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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置监听器用于把实例交给spring容器管理-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--设置配置文件的路径,-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--整合springmvc-->
<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>
<!-- 因为tomcat的默认启动资源文件是index.jsp,修改默认启动首页-->
<welcome-file-list>
<welcome-file>login.html</welcome-file>
<welcome-file>login.htm</welcome-file>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
五 、Spring整合Mybatis
5.1 新建 spring-mybatis.xml 配置文件,在配置文件中配置mybatis 相关内容。配置如下:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!--配置 c3p0 数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置SqlSessionFactory 工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置扫描Dao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dongl.dao"/>
</bean>
</beans>
5.2 在applicationContext.xml 配置文件中,引入 spring-mybatis.xml 配置。
<!--引入mybatis 的配置-->
<import resource="spring-mybatis.xml"/>
5.3 在配置完以上配置后,即可对数据库进行查询操作,添加事务之后可进行其他操作。
在Dao 层添加注解 @Repository
@Repository
public interface UserDao {
@Select("SELECT * FROM `user`")
public List<User> findAll();
}
在service 层进行接口注入
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> findAll() {
System.out.println("userService 的findAll 查询");
List<User> userList = userDao.findAll();
return userList;
}
}
5.4 添加事务处理
在spring-mybatis.xml 文件 中添加 事务配置,具体配置如下:
<!-- 事务控制的配置 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 事务控制数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事务增强,事务如何切入 -->
<tx:advice id="txAdvice">
<tx:attributes>
<!-- 表示所有方法都是事务方法 -->
<tx:method name="*" />
<!-- 以get和find开始的方法都是仅读方法 -->
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 开启基于注释的事务,使用xml配置形式的事务(推荐使用配置的方式) -->
<aop:config>
<!-- 切入表达式(所有返回值类型的service包下或者子包下的所有类中任意多的参数的方法都可以切入) -->
<aop:pointcut id="txPointCut" expression="execution(* com.dongl.service..*(..))" />
<!-- 指定事务增强的规则 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
进行数据保存测试
在Dao层实现如下:
@Insert("INSERT INTO `user` (username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address});")
public int save(User user);
spring-mybatis.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-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/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">
<!--配置 c3p0 数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springmvc04"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置SqlSessionFactory 工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- mybaits的全局配置文件
<property name="configuration" value="classpath:mybatis-config.xml"></property>
-->
<!-- 指定数据库的数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 指定mybatis,mapper文件的位置
<property name="mapperLocations" value="classpath:mapper/*-mapper.xml"></property>-->
</bean>
<!--配置扫描Dao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dongl.dao"/>
</bean>
<!-- 事务控制的配置 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 事务控制数据源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事务增强,事务如何切入 -->
<tx:advice id="txAdvice">
<tx:attributes>
<!-- 表示所有方法都是事务方法 -->
<tx:method name="*" />
<!-- 以get和find开始的方法都是仅读方法 -->
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 开启基于注释的事务,使用xml配置形式的事务(推荐使用配置的方式) -->
<aop:config>
<!-- 切入表达式(所有返回值类型的service包下或者子包下的所有类中任意多的参数的方法都可以切入) -->
<aop:pointcut id="txPointCut" expression="execution(* com.dongl.service..*(..))" />
<!-- 指定事务增强的规则 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>