SSM三大框架整合

Spring+SpringMVC+MyBatis ,利用Spring整合SpringMVC和MyBatis 。

1. 创建数据库和表结构

SQL语句

2. 创建maven工程

引入坐标依赖

  1. 创建ssm_parent父工程(打包方式选择pom,必须的)
  2. 创建ssm_web子模块(打包方式是war包)
  3. 创建ssm_service子模块(打包方式是jar包)
  4. 创建ssm_dao子模块(打包方式是jar包)
  5. 创建ssm_domain子模块(打包方式是jar包)
  6. web依赖于service,service依赖于dao,dao依赖于domain
  7. 在ssm_parent的pom.xml文件中引入坐标依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</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-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
</dependencies>

3. 创建对应的目录结构

目录结构

4. 配置Spring

编写Spring配置文件applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

<!--开启注解扫描 希望处理service和dao,但是controller不需要Spring框架去处理-->
<context:component-scan base-package="com.ligangit">
<!--配置controller不扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>

将AccountServiceImpl.java添加到容器,测试

1
2
3
4
5
6
7
8
9
10
11
12
13
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
@Override
public List<Account> findAll() {
System.out.println("service层,查询所有账户。。。");
return null;
}
@Override
public void saveAccount(Account account) {
System.out.println("service层,保存账户信息。。。");

}
}

测试

1
2
3
4
5
6
7
8
9
10
11
//    测试Spring框架
@Test
public void testSpring1(){
// 加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 获取对象
AccountService accountService = (AccountService) applicationContext.getBean("accountService");
// 调用方法
accountService.findAll();
}

5. 配置SpringMVC

  1. 在web.xml中配置前端控制器DispatcherServlet

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <!--配置前端控制器-->
    <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--设置配置文件路径-->
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--设置项目启动时DispatcherServlet加载一次-->
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <!--表示任意请求都会经过servlet-->
    <url-pattern>/</url-pattern>
    </servlet-mapping>
  2. 在web.xml中配置过滤器解决中文乱码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!--配置解决中文乱码的过滤器-->
    <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>
    </filter>
    <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
  3. 编写Springmvc的配置文件springmvc.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    <?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.ligangit"/>
    <!--视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"/>
    <property name="suffix" value=".jsp"/>
    </bean>

    <!--配置文件解析器 id值必须是multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--设置上传文件最大10M,即10*1024*1024=10485760-->
    <property name="maxUploadSize" value="10485760"/>
    </bean>

    <!--前端控制器,哪些静态资源不拦截-->
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
    <mvc:resources mapping="/css/**" location="/css/"></mvc:resources>

    <!--开启SpringMVC框架注解支持-->
    <mvc:annotation-driven conversion-service="conversionService"/>
    </beans>
  4. 测试SpringMVC的框架是否搭建成功

    1. 编写index.jsp和list.jsp,编写超链接

      1
      <a href="account/findAll">测试SpringMVC</a>
    2. 创建AccountController类,编写方法,进行测试

      1
      2
      3
      4
      5
      6
      7
      8
      9
      @Controller
      @RequestMapping("/account")
      public class AccountController {
      @RequestMapping("/findAll")
      public String findAll(){
      System.out.println("Controller查询所有账户...");
      return "list";
      }
      }

6. Spring整合SpringMVC框架

  1. 目的:在Controller中能成功的调用Service对象中的方法。

  2. 在项目启动的时候,就去加载Spring的配置文件applicationContext.xml,在web.xml中配置ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml配置文件)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <!--配置Spring的监听器 默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
    <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>

7. 配置Mybatis

  1. 编写dao层的SQL

    1
    2
    3
    4
    5
    6
    7
    8
    public interface AccountDao {
    // 查询所有账户
    @Select("select * from account")
    public List<Account> findAll();
    // 保存账户信息
    @Insert("insert into account (name,money) values (#{name},#{money})")
    public void saveAccount(Account account);
    }
  2. 在web项目中编写MyBatis配置文件mybatis-config.xml,characterEncoding设置编码格式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    <!--配置环境-->
    <environments default="mysql">
    <environment id="mysql">
    <transactionManager type="JDBC"></transactionManager>
    <dataSource type="POOLED">
    <property name="url" value="jdbc:mysql:///ssm?characterEncoding=utf8" />
    <property name="username" value="root" />
    <property name="password" value="123456" />
    <property name="driver" value="com.mysql.jdbc.Driver" />
    </dataSource>
    </environment>
    </environments>

    <!--引入映射配置文件-->
    <mappers>
    <!--<mapper class="com.ligangit.dao.AccountDao"/>-->
    <package name="com.ligangit.dao"/>
    </mappers>

    </configuration>
  3. 测试

    注意:添加、修改、删除操作需要提交事务

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    /**
    * 测试查询
    */
    @Test
    public void testMybatis() throws IOException {
    //加载配置文件
    InputStream inputStream = Resources.getResourceAsStream("mybatis/mybatis-config.xml");
    // 创建SqlSessionFactory对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //创建SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    // 获取到代理对象
    AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
    //查询所有数据
    List<Account> accountList = accountDao.findAll();
    for (Account account:accountList){
    System.out.println(account);
    }
    //关闭资源
    sqlSession.close();
    inputStream.close();
    }
    /**
    * 测试保存
    */
    @Test
    public void testMybatis2() throws IOException {
    Account account=new Account();
    account.setName("小白");
    account.setMoney(400d);
    //加载配置文件
    InputStream inputStream = Resources.getResourceAsStream("mybatis/mybatis-config.xml");
    // 创建SqlSessionFactory对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //创建SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    // 获取到代理对象
    AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
    //保存
    accountDao.saveAccount(account);
    //提交事务
    sqlSession.commit();
    //关闭资源
    sqlSession.close();
    inputStream.close();
    }
  4. 结果

    结果

8. Spring整合Mybatis框架

在Spring配置文件applicationContext.xml中配置Mybatis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!--Spring整合Mybatis框架-->
<!--配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!--配置SqlSessionFactory工厂-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置AccountDao接口所在包-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ligangit.dao"/>
</bean>

将dao注入容器

1
2
@Repository
public interface AccountDao {

service层调用dao

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("service层,查询所有账户。。。");
return accountDao.findAll();
}
@Override
public void saveAccount(Account account) {
System.out.println("service层,保存账户信息。。。");
accountDao.saveAccount(account);
}
}

MyBatis配置文件mybatis-config.xml可以删除了

9. Spring整合Mybatis框架配置事务

配置Spring框架声明式事务管理,用于添加、修改、删除操作提交。

在Spring配置文件applicationContext.xml中配置声明式事务管理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!--配置Spring框架声明式事务管理,用于添加、修改、删除操作提交-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ligangit.service.impl.*ServiceImpl.*(..))"/>
</aop:config>

测试:

​ jsp页面:

1
2
3
4
5
6
7
8
<a href="account/findAll">测试SpringMVC</a>
<br>
<br>
<form action="account/saveAccount" method="post">
姓名:<input type="text" name="name" /></br>
金额:<input type="text" name="money" /></br>
<input type="submit" value="提交">
</form>

​ 控制器代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
AccountService accountService;
/**
* 查询所有账户
*/
@RequestMapping("/findAll")
public String findAll(Model model){
System.out.println("Controller查询所有账户...");
// 调用service的方法
List<Account> accountList = accountService.findAll();
model.addAttribute("list", accountList);
return "list";
}

/**
* 保存账户
*/
@RequestMapping("/saveAccount")
public void saveAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("Controller保存账户...");
// 调用service的方法
accountService.saveAccount(account);
response.sendRedirect(request.getContextPath()+"/account/findAll");
return;
}
}

最后更新: 2020年07月13日 23:02

原始链接: http://ligangit.com/2020/07/12/SSM三大框架整合/

× 请我吃糖~
打赏二维码