SSM框架学习总结第四篇--SSM框架整合

    科技2024-10-24  10


    SSM框架系列文章: SSM框架学习总结第零篇–框架是什么 SSM框架学习总结第一篇–MyBatis SSM框架学习总结第二篇–Spring SSM框架学习总结第三篇–Spring MVC SSM框架学习总结第四篇–SSM框架整合


    文章目录

    前言一、环境准备1.1 创建数据库与表结构1.2 创建Maven工程1.3 导入坐标并建立依赖1.4 编写实体类1.5 编写业务接口1.6 编写持久层接口 二、整合2.1 保证 Spring 框架在 web 工程中独立运行2.1.1 :编写 spring 配置文件并导入约束2.1.2 使用注解配置业务层和持久层2.1.3 测试 spring 能否独立运行 2.2 保证 SpringMVC 在 web 工程中独立运行2.2.1 在 web.xml 中配置核心控制器(DispatcherServlet)2.2.2 编写 SpringMVC 的配置文件2.2.3 编写 Controller 和 jsp 页面 2.3 整合 Spring 和 SpringMVC2.3.1 配置监听器实现启动服务创建容器 2.4 保证 MyBatis 框架在 web 工程中独立运行2.4.1 编写 AccountDao 映射配置文件2.4.2 编写 SqlMapConfig 配置文件2.4.3 测试运行结果 2.5 整合 Spring 和 MyBatis2.5.1 Spring 接管 MyBatis 的 Session 工厂2.5.2 配置自动扫描所有 Mapper 接口和文件2.5.3 配置 spring 的事务2.5.4 测试整合结果 2.6 测试 SSM 整合结果2.6.1 编写测试 jsp2.6.2 修改控制器中的方法2.6.3 测试结果 总结


    前言


    提示:以下是本篇文章正文内容

    一、环境准备

    1.1 创建数据库与表结构

    create database ssm; create table account( id int primary key auto_increment, name varchar(100), money double(7,2), );

    1.2 创建Maven工程

    创建子模块: ssm_domain jar ssm_dao jar ssm_service jar ssm_web war

    1.3 导入坐标并建立依赖

    注意 MyBatis 和 Spring 的版本对应关系:

    <?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>cn.itcast</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.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</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-webmvc</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>compile</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</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.0.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.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</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>

    1.4 编写实体类

    /** * 帐户 */ public class Account implements Serializable{ private Integer id; private String name; private Double money; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }

    1.5 编写业务接口

    public interface AccountService { // 查询所有账户 public List<Account> findAll(); // 保存帐户信息 public void saveAccount(Account account); }

    1.6 编写持久层接口

    /** * 帐户dao接口 */ public interface IAccountDao { /** * 保存 * @param account */ void save(Account account); /** * 查询所有 * @return */ List<Account> findAll(); }

    二、整合

    2.1 保证 Spring 框架在 web 工程中独立运行

    2.1.1 :编写 spring 配置文件并导入约束

    <?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置 spring 创建容器时要扫描的包 --> <context:component-scan base-package="com.itheima"> <!--制定扫包规则,不扫描@Controller 注解的 JAVA 类,其他的还是要扫描 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> </beans>

    2.1.2 使用注解配置业务层和持久层

    /** * 账户的业务层实现类 */ @Service("accountService") public class AccountServiceImpl implements IAccountService { @Autowired private IAccountDao accountDao; @Override public List<Account> findAllAccount() { return accountDao.findAllAccount(); } @Override public void saveAccount(Account account) { accountDao.saveAccount } } //持久层实现类代码: //此时不要做任何操作,就输出一句话。目的是测试 spring 框架搭建的结果。 /** * 账户的持久层实现类 */ @Repository("accountDao") public class AccountDaoImpl implements IAccountDao { @Override public List<Account> findAllAccount() { System.out.println("查询了所有账户"); return null; } @Override public void saveAccount(Account account) { System.out.println("保存了账户"); } }

    2.1.3 测试 spring 能否独立运行

    /** * 测试 spring 环境搭建是否成功 */ public class Test01Spring { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class); as.findAllAccount(); } }

    结果:

    2.2 保证 SpringMVC 在 web 工程中独立运行

    2.2.1 在 web.xml 中配置核心控制器(DispatcherServlet)

    <?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" version="2.5"> <display-name>ssm_web</display-name> <!-- 配置 spring mvc 的核心控制器 --> <servlet> <servlet-name>springmvcDispatcherServlet</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> <!-- 配置 servlet 的对象的创建时间点:应用加载时创建。取值只能是非 0 正整数,表示启动顺 序 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvcDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置 springMVC 编码过滤器 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-cla ss> <!-- 设置过滤器中的属性值 --> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <!-- 启动过滤器 --> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <!-- 过滤所有请求 --> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>

    2.2.2 编写 SpringMVC 的配置文件

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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.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"> <!--开启注解扫描,只扫描Controller注解--> <context:component-scan base-package="cn.itcast"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--配置的视图解析器对象--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--开启SpringMVC注解的支持--> <mvc:annotation-driven/> </beans>

    2.2.3 编写 Controller 和 jsp 页面

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>主页</title> </head> <body> <a href="account/findAllAccount">访问查询账户</a> </body> </html> /** * 账户的控制器 */ @Controller("accountController") @RequestMapping("/account") public class AccountController { @RequestMapping("/findAllAccount") public String findAllAccount() { System.out.println("执行了查询账户"); return "success"; } }

    结果:

    2.3 整合 Spring 和 SpringMVC

    2.3.1 配置监听器实现启动服务创建容器

    <!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。 该间监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!-- 手动指定 spring 配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>

    2.4 保证 MyBatis 框架在 web 工程中独立运行

    2.4.1 编写 AccountDao 映射配置文件

    注意:我们使用代理 dao 的方式来操作持久层,所以此处 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.itheima.dao.IAccountDao"> <!-- 查询所有账户 --> <select id="findAll" resultType="com.itheima.domain.Account"> select * from account </select> <!-- 新增账户 --> <insert id="save" parameterType="com.itheima.domain.Account"> insert into account(name,money) values(#{name},#{money}); </insert> </mapper>

    2.4.2 编写 SqlMapConfig 配置文件

    <?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> <properties resource="jdbcConfig.properties"></properties> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="pooled"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/itheima/dao/AccountDao.xml"/> </mappers> </configuration> properties 文件中的内容: jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm jdbc.username=root jdbc.password=1234

    2.4.3 测试运行结果

    public class TestMyBatis { /** * 测试查询 * @throws Exception */ @Test public void run1() throws Exception { // 加载配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); // 创建SqlSessionFactory对象 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession对象 SqlSession session = factory.openSession(); // 获取到代理对象 AccountDao dao = session.getMapper(AccountDao.class); // 查询所有数据 List<Account> list = dao.findAll(); for(Account account : list){ System.out.println(account); } // 关闭资源 session.close(); in.close(); } /** * 测试保存 * @throws Exception */ @Test public void run2() throws Exception { Account account = new Account(); account.setName("熊大"); account.setMoney(400d); // 加载配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); // 创建SqlSessionFactory对象 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession对象 SqlSession session = factory.openSession(); // 获取到代理对象 AccountDao dao = session.getMapper(AccountDao.class); // 保存 dao.saveAccount(account); // 提交事务 session.commit(); // 关闭资源 session.close(); in.close(); } }

    2.5 整合 Spring 和 MyBatis

    整合思路: 把 mybatis 配置文件(SqlMapConfig.xml)中内容配置到 spring 配置文件中 同时,把 mybatis 配置文件的内容清掉。 注意: 由于我们使用的是代理 Dao 的模式,Dao 具体实现类由 MyBatis 使用代理方式创建,所以此时 mybatis配置文件不能删。 当我们整合 spring 和 mybatis 时,mybatis 创建的 Mapper.xml 文件名必须和 Dao 接口文件名一致

    2.5.1 Spring 接管 MyBatis 的 Session 工厂

    <!-- 加载配置文件 --> <context:property-placeholder location="classpath:jdbcConfig.properties" /> <!--Spring整合MyBatis框架--> <!--配置连接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--配置SqlSessionFactory工厂--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean>

    2.5.2 配置自动扫描所有 Mapper 接口和文件

    <!-- 配置 Mapper 扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itheima.dao"/> </bean>

    2.5.3 配置 spring 的事务

    <!--配置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(* cn.itcast.service.impl.*ServiceImpl.*(..))"/> </aop:config>

    2.5.4 测试整合结果

    /** * 测试 spring 整合 mybatis */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations= {"classpath:applicationContext.xml"}) public class Test03SpringMabatis { @Autowired private IAccountService accountService; @Test public void testFindAll() { List list = accountService.findAllAccount(); System.out.println(list); } @Test public void testSave() { Account account = new Account(); account.setName("测试账号"); account.setMoney(1234f); accountService.saveAccount(account); } }

    2.6 测试 SSM 整合结果

    2.6.1 编写测试 jsp

    请求发起页面:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>主页</title> </head> <body> <a href="account/findAllAccount">访问查询账户</a> <hr/> <form action="account/saveAccount" method="post"> 账户名称:<input type="text" name="name"/><br/> 账户金额:<input type="text" name="money"><br/> <input type="submit" value="保存"/> </form> </body> </html>

    响应结果页面:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>账户的列表页面</title> </head> <body> <table border="1" width="300px"> <tr> <th>编号</th> <th>账户名称</th> < th>账户金额</th> </tr> <c:forEach items="${accounts}" var="account" varStatus="vs"> <tr> <td>${vs.count}</td> <td>${account.name }</td> <td>${account.money }</td> </tr> </c:forEach> </table> </body> </html>

    2.6.2 修改控制器中的方法

    /** * 账户的控制器 */ @Controller("accountController") @RequestMapping("/account") public class AccountController { @Autowired private IAccountService accountService; /** * 查询所有账户 * @return */ @RequestMapping("/findAllAccount") public ModelAndView findAllAccount() { List<Account> accounts = accountService.findAllAccount(); ModelAndView mv = new ModelAndView(); mv.addObject("accounts", accounts); mv.setViewName("accountlist"); return mv; } /** * 保存账户 * @param account * @return */ @RequestMapping("/saveAccount") public String saveAccount(Account account) { accountService.saveAccount(account); return "redirect:findAllAccount"; } }

    2.6.3 测试结果


    总结

    这里对文章进行总结:本文对前三篇的学习进行了一个整合,将Spring,MyBatis,Spring MVC三个框架进行了整合。整合过程设计到了各部分代码的编写与测试。 SSM框架学习总结到这也算告一段落了,希望大家继续努力,最后拿到满意的offer!


    **如果各位大佬觉得有用,请给个赞吧。**


    Processed: 0.025, SQL: 8