SSM三大框架整合
1、搭建整合环境
SSM整合有多种方式,这里选择XML + 注解的方式,SSM三大框架使用版本:spring-webmvc5.0.2、spring5.0.2、mybatis3.4.5
1.创建数据库和表结构
create database ssm; use ssm; create table account( id int primary key auto_increment, name varchar(20), money double(20,2) );
2.创建maven工程,定义pom.xml文件
设置编译插件和Tomcat插件:
<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> </properties>
<!-- 设置编译插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version > <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <!-- 设置Tomcat插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <port>8080</port> </configuration> </plugin>
锁定依赖版本:
<properties> <spring.version>5.0.2.RELEASE</spring.version> <springmvc.version>5.0.2.RELEASE</springmvc.version> <mybatis.version>3.4.5</mybatis.version> </properties>
<!--锁定依赖版本--> <dependencyManagement> <dependencies> <!-- Mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- springMVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springmvc.version}</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</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> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> </dependencies> </dependencyManagement>
添加依赖:
<dependencies> <!-- Mybatis 和 mybatis 与 spring 的整合 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- MySql 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency> <!-- druid 数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> <!-- springMVC 核心--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <!-- spring 相关 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <!-- junit 测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <!-- jsp --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
3.持久层(如果使用注解方式开发,则只需要在接口方法上添加相应的注解,删除 mapper 映射文件,其他配置都不需要变)
定义实体类:
/** * 账户实体类 */ public class Account { private Integer id; private String name; private Double money; // get 和 set 方法 }
dao 代码:
/** * 账户持久层接口 */ public interface AccountDao { /** * 根据id查询账户信息 * @param id * @return */ Account findById(Integer id); }
配置文件:在 src/main/resources 下创建
使用xml开发,映射文件:AccountDao.xml
要求名称和 dao 接口名一样,后面配置的 mapper 扫描器以此规则来扫描(放置在和dao接口相同的包路径下,方便管理)
<?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.fgy.ssm.dao.AccountDao"> <select id="findById" parameterType="int" resultType="account"> select * from account where id = #{id} </select> </mapper>
创建 spring 配置文件:applicationContext.xml,把原本属于 mybatis 的配置文件内容交给 spring 来管理
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- ================= dao层配置文件开始 ================= --> <!-- 数据库连接池 驱动,url,用户名,密码可以配置到别的文件中,方便修改 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <!-- 驱动 --> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <!-- url --> <property name="url" value="jdbc:mysql://localhost:3306/ssm" /> <!-- 用户名 --> <property name="username" value="root" /> <!-- 密码 --> <property name="password" value="root" /> </bean> <!-- mapper 配置 --> <!-- 让 spring 管理 sqlsessionFactory ,每次使用时创建 sqlSession ,使用mybatis和spring整合包中的类 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据库连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 给实体类起别名 --> <property name="typeAliasesPackage" value="com.fgy.ssm.domain"></property> </bean> <!-- mapper 扫描器 :用来产生代理对象 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 可以使用分号或逗号作为分隔符设置多于一个的包路径 mapper 映射文件名称必须和 dao 接口名一样才能扫描 --> <property name="basePackage" value="com.fgy.ssm.dao"></property> </bean> <!-- ================= dao层配置文件结束 ================= --> <!-- ================= service层配置文件开始 ================= --> <!-- ================= service层配置文件结束 ================= --> </beans>
添加日志文件 log4j.properties
.......................................
测试持久层:
public class AccountDaoTest { @Test public void testFindById() { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); AccountDao accountDao = context.getBean(AccountDao.class); Account account = accountDao.findById(1); System.out.println(account); } }
也可以使用 spring 整合 junit 来测试,坐标在最开始时已经导入
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class AccountDaoTest { @Autowired private AccountDao accountDao; @Test public void testFindById() { Account account = accountDao.findById(1); System.out.println(account); } }
4.业务层
dao 新增的方法:这里使用注解,不再使用 xml
/** * 根据名称查询账户信息 * @param name * @return */ @Select("select * from account where name = #{name}") Account findByName(String name); /** * 更新账户信息 * @param account1 */ @Select("update account set name = #{name}, money = #{money} where id = #{id}") void update(Account account1);
service 代码:
/** * 账户业务层接口 */ public interface AccountService { /** * 根据id查询账户信息 * @param id * @return */ Account findById(Integer id); /** * 用户1向用户2转账 * @param user1 * @param user2 * @param money */ void transfer(String user1, String user2, Double money); }
/** * 账户业务层实现类 */ @Service("accountService") public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; /** * 根据id查询账户信息 * @param id * @return */ @Override public Account findById(Integer id) { return accountDao.findById(id); } /** * 用户1向用户2转账 * @param user1 * @param user2 * @param money */ @Override public void transfer(String user1, String user2, Double money) { // 查询用户1 Account account1 = accountDao.findByName(user1); // 查询用户2 Account account2 = accountDao.findByName(user2); // 转账 account1.setMoney(account1.getMoney() - money); account2.setMoney(account2.getMoney() + money); // 更新用户1 accountDao.update(account1); // int i = 1/0; // 更新用户2 accountDao.update(account2); } }
配置文件:在 applicationContext.xml 中添加
<!-- ================= service层配置文件开始 ================= --> <!-- 开启注解扫描(使用注解开发) --> <context:component-scan base-package="com.fgy.ssm.service.impl"/> <!-- 事务配置 --> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true" propagation="SUPPORTS"/> <tx:method name="*" read-only="false" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 配置 aop --> <aop:config> <!-- 配置切入点表达式 --> <aop:pointcut id="pt" expression="execution(* com.fgy.ssm.service.impl.*.*(..))"/> <!-- 配置切入点表达式和事务通知的对应关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"></aop:advisor> </aop:config> <!-- ================= service层配置文件结束 ================= -->
测试业务层:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext.xml") public class AccountServiceTest { @Autowired private AccountService accountService; @Test public void testTransfer() { accountService.transfer("张三", "李四", 100.0); } }
表现层:
controller 代码:
/** * 账户表现层 */ @Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; /** * 查询账户详情 * @param model * @param id * @return */ @RequestMapping("/findDetail/{id}") public String findDetail(Model model, @PathVariable(name = "id") Integer id) { Account account = accountService.findById(id); model.addAttribute("account", account); return "detail"; } /** * 测试转账 * @return */ @RequestMapping("/transfer") public String transfer() { accountService.transfer("张三", "李四", 100.0); return "success"; } }
新建 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: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-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- 开启注解扫描 --> <context:component-scan base-package="com.fgy.ssm.controller"/> <!-- 处理器映射器、处理器适配器 默认注册处理请求,参数和返回值的类。主要实现了两个接口:HandlerMapping与HandlerAdapter。 --> <mvc:annotation-driven/> <!-- 静态资源不拦截 --> <mvc:default-servlet-handler/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
index.jsp 页面和 detail.jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>index</title> </head> <body> <a href="${pageContext.request.contextPath}/account/findDetail/1">查询详情</a> <br/> <a href="${pageContext.request.contextPath}/account/transfer">测试事务是否正常</a> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>detail</title> </head> <body> id:${account.id} <br/> name:${account.name} <br/> money:${account.money} <br/> <img src="${pageContext.request.contextPath}/images/test.jpg">测试静态文件是否放行 </body> </html>
配置 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 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_3_0.xsd" version="3.0"> <!-- 配置过滤器,解决中文乱码的问题 --> <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> <!-- forceEncoding=true意思是指无论客户端请求是否包含了编码,都用过滤器里的编码来解析请求 --> <init-param> <param-name>forceEncoding</param-name> <param-value>false</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置 spring 核心监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- ContextLoaderListener 默认去WEB-INF下加载名称为applicationContext.xml文件 重新指定配置文件的路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置 SpringMVC的核心控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置Servlet的初始化参数,读取springmvc的配置文件,创建spring容器 如果不指定,默认读取 /WEB-INF/dispatcherServlet-servlet.xml文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 配置servlet启动时加载对象,servlet默认发起请求时才创建,这里是加载配置文件,启动时就需要加载 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
启动 Tomcat 测试:
..........................
最后:为什么不把 springMVC 的配置移到 spring 配置文件中呢?或者说把两个配置文件内容合在一起,只保留一个配置文件。
参考博文:https://blog.csdn.net/f45056231p/article/details/81545964