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-8project.build.sourceEncoding> <maven.compiler.source>1.8maven.compiler.source> <maven.compiler.target>1.8maven.compiler.target> properties>
<plugin> <groupId>org.apache.maven.pluginsgroupId> <artifactId>maven-compiler-pluginartifactId> <version>3.1version > <configuration> <source>${maven.compiler.source}source> <target>${maven.compiler.target}target> <encoding>${project.build.sourceEncoding}encoding> configuration> plugin> <plugin> <groupId>org.apache.tomcat.mavengroupId> <artifactId>tomcat7-maven-pluginartifactId> <version>2.2version> <configuration> <path>/path> <port>8080port> configuration> plugin>
锁定依赖版本:
<properties> <spring.version>5.0.2.RELEASEspring.version> <springmvc.version>5.0.2.RELEASEspringmvc.version> <mybatis.version>3.4.5mybatis.version> properties>
<dependencyManagement> <dependencies> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatisartifactId> <version>${mybatis.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>${springmvc.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-contextartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-coreartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-aopartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-expressionartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-beansartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-aspectsartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-context-supportartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>${spring.version}version> <scope>testscope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-txartifactId> <version>${spring.version}version> dependency> dependencies> dependencyManagement>
添加依赖:
<dependencies> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatisartifactId> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatis-springartifactId> <version>1.3.1version> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>5.1.32version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>druidartifactId> <version>1.0.9version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-contextartifactId> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-coreartifactId> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-aopartifactId> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-expressionartifactId> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-beansartifactId> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-aspectsartifactId> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-context-supportartifactId> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <scope>testscope> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-txartifactId> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.12version> <scope>testscope> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>servlet-apiartifactId> <version>2.5version> <scope>providedscope> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>jsp-apiartifactId> <version>2.0version> <scope>providedscope> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>jstlartifactId> <version>1.2version> 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"> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/ssm" /> <property name="username" value="root" /> <property name="password" value="root" /> bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.fgy.ssm.domain">property> bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.fgy.ssm.dao">property> bean> 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 中添加
<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:config> <aop:pointcut id="pt" expression="execution(* com.fgy.ssm.service.impl.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt">aop:advisor> aop:config>
测试业务层:
@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"/> <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>indextitle> 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>detailtitle> 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>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>falseparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
启动 Tomcat 测试:
..........................
最后:为什么不把 springMVC 的配置移到 spring 配置文件中呢?或者说把两个配置文件内容合在一起,只保留一个配置文件。
参考博文:https://blog.csdn.net/f45056231p/article/details/81545964