SSM之整合

本文详细介绍Spring、SpringMVC及MyBatis(简称SSM)框架的整合过程,包括环境搭建、配置文件详解、测试代码编写等内容。通过实战案例演示如何实现业务逻辑层和服务层的整合,以及SpringMVC与MyBatis的配置与使用。
摘要由CSDN通过智能技术生成

1 ssm整合说明

  • (1)SSM是什么?
    Spring,SpringMVC,Mybastis
  • (2)为什么要专门训练SSM
    要开发一个项目,首先是搭建SSM环境,之后才能开发其他功能
  • (3)整合思路是什么?
    》》1.先搭建整合的环境
    》》2.先把Spring的配置搭建完成
    》》3.再使用Spring整合SpringMVC框架
    》》4.最后使用Spring整合MyBatis框架
  • (4)SSM整合可以使用多种方式,咱们会选择XML + 注解的方式

2 搭建环境

  • (1)数据库创建ssm
  • (2)创建maven工程
  • (3)properties给谁用?
  • (4)依赖框架
  • (5)log4j
    准备数据库sql
create database ssm;
 use ssm;
create table account(
id int primary key auto_increment, name varchar(20),
money double
);

创建模块SSM01
在这里插入图片描述

pom.xml

 <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.2.9.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>test</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>

log4j.properties

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\ssm.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

3 编写Spring框架测试代码IOC&DI

  • (1)编写业务类调用测试逻辑
    》TestPersonService
    》IPersonService PersonServiceImpl
    》Person
  • (2)applicationContext.xml
  • (3)配置组件扫描 – 验证IOC
  • (4)配置哪些不扫描
  • (5)验证DI
    》IPersonDao PersonDaoImpl
    TestPersonService
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestPersonService {
    private static final Logger log = Logger.getLogger(TestPersonService.class.getName());
   @Autowired
   IPersonService personService;
    @Test
    public void test01(){//编写两个业务功能 查找所有的person 保存一个person
       //创建业务对象
       //IPersonService personService = new PersonServiceImpl();
       //调用查询
       log.info(personService+"");
       List<Person> list = personService.findAll();
       //调用保存
       log.info(list+"");
       Person person = new Person("jack",100.00);
       personService.savePerson(person);

        List<Person> list1 = personService.findAll();
        log.info(list1+"");
    }

    @Test
    public void test02(){//DI
        System.out.println(personService);
    }
}

Person

public class Person {
    private Integer id;
    private String name;
    private Double money;

    public Person() {
    }

    public Person(String name, Double money) {
        this.name = name;
        this.money = money;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

**IPersonService **

public interface IPersonService {
    //显示所有的Person数据
    List<Person> findAll();
    //保存一个Person数据
    void savePerson(Person person);
}

**PersonServiceImpl **

@Service
public class PersonServiceImpl implements IPersonService {
    @Autowired
    private IPersonDao iPersonDao;
    @Override
    public List<Person> findAll() {
        List<Person> list = iPersonDao.findAll(); //测试IOC时写打印语句 
        return list;
    }

    @Override
    public void savePerson(Person person) {
        iPersonDao.save(person);//测试IOC时写打印语句 
    }
}

applicationContext.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.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--设置扫描包,包下设置注解@Service @Repository @Component @AutoWried-->
    <context:component-scan base-package="com.syy">
    <!--由于springmvc的controller是由springmvc来扫描,需要将controller排除在外-->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

**IPersonDao **

public interface IPersonDao {
    // 一般都是 CRUD
    //创建 add save
    //find  findById findAll
    //update updateById
    //deleteById  deleteByIds
    List<Person> findAll();
    void save(Person person);
}

PersonDaoImpl

@Repository
public class PersonDaoImpl implements IPersonDao {
    @Override
    public List<Person> findAll() {
        System.out.println("findAll dao");
        return null;
    }
    
    @Override
    public void save(Person person) {
        System.out.println("save dao");
    }
}

4 Spring整合SpringMVC的框架1

  • (1)web.xml中配置前端控制器DispatcherServlet
    SpringMVC的核心就是DispatcherServlet,DispatcherServlet实质也是一个HttpServlet。DispatcherSevlet负责将请求分发,所有的请求都有经过它来统一分发。
  • (2)web.xml中配置编码过滤器CharacterEncodingFilter
    在 SpringMVC 中,框架直接给我们提供了一个用来解决请求和响应的乱码问题的过滤器 CharacterEncodingFilter
  • (3)web.xml中配置编码监听器ContextLoaderListener
    web.xml中的配置文件中ContextLoaderListener作为监听器,会监听web容器相关事件,在web容器启动或者关闭时触发执行响应程序

web.xml 配置DispatcherServlet,CharacterEncodingFilter,ContextLoaderListener

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>
  <display-name>Archetype Created Web Application</display-name>

  <!--设置配置文件的路径  service dao-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <!--解决中文乱码的过滤器-->
  <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>

  <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--配置前端控制器  controller-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动服务器,创建该servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>

5 Spring整合SpringMVC的框架2

  • (1)springmvc中配置视图解析器,组件扫描,注解驱动
  • (2)配置springmvc对资源文件的放行
  • (3)编写一个PersonController测试
  • (4)编写一个list.jsp页面进行展示数据

配置springmvc.xml

<?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">
        <!--springmvc是web层  UserController  @Controller -->
    <!-- 打开组件扫描-->
    <context:component-scan base-package="com.syy">
         <!-- 只处理带@Controller的请求-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置的视图解析器对象 /WEB-INF/pages/success.jsp -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--过滤静态资源 .js .css png-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <!--开启SpringMVC注解的支持 @RequestMapping @RequestBody @ResponseBody-->
    <mvc:annotation-driven/>
</beans>

**PersonController **

@Controller
@RequestMapping("/person")
public class PersonController {
    @Autowired
    private IPersonService personService;

    @RequestMapping(path="/list",method = RequestMethod.GET)
    public String list(Model model){
        //显示所有的person数据
        List<Person> list = personService.findAll();
        System.out.println("list() list= "+list);
        //数据放在Model对象,由Model传给页面
        model.addAttribute("list",list);//参1 key  参2 value
        return "list";
    }
}

list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1px" width="100%">
    <c:forEach items="${list}" var="person">
         <tr>
             <td>${person.id}</td>
             <td>${person.name}</td>
             <td>${person.money}</td>
         </tr>
    </c:forEach>
</table>
</body>
</html>

6 编写Mybatis框架

  • (1)SqlMapConfig.xml
    》》指定四大信息
    》》指定domain别名
    》》指定映射文件
  • (2)编写测试
    》》保存
    》》查询
<?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>
    <!-- 别名  com.wzx.domain.Person  person-->
    <typeAliases>
        <package name="com.syy.domain"/>
    </typeAliases>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 核心 配置文件扫描到映射文件-->
    <mappers>
        <package name="com.wzx.dao"/>
    </mappers>
</configuration>

TestMyBatis

public class TestMyBatis {
    private  SqlSession session;
    @Before
    public void init(){
        // 加载配置文件
        InputStream in = TestMyBatis.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
        // 创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 创建SqlSession对象
         session = factory.openSession();
    }
    @After
    public void destory(){
        session.commit();
        session.close();
    }
    @Test
    public void test01(){
        //最核心对象是session
        //System.out.println(session);
        //Mybastis的特点是sql与代码是分开的,需要映射文件
        IPersonDao dao =  session.getMapper(IPersonDao.class);
        List<Person> list = dao.findAll();
        System.out.println(list);
    }
    @Test
    public void test02(){
        //最核心对象是session
        IPersonDao dao =  session.getMapper(IPersonDao.class);
        dao.save(new Person("tony",200.00));

    }
}

IPersonDao.xml

<?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.syy.dao.IPersonDao">
    <select id="findAll" resultType="person">
            select * from person;
    </select>

    <insert id="save" parameterType="person">
        insert into person (name,money)values(#{name},#{money})
    </insert>
</mapper>

7 Spring整合MyBatis框架

  • (1)Spring整合MyBatis需要添加整合包
  • (2)什么是mybatis-spring
    MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中
    不需要调用 session.getMapper(IpersonDao.class)
    session.commit()
    session.close()
    pom.xml
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

applicationContext.xml

    <!-- 四大信息-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
    <!-- session工厂-->
    <bean id="sqlSessionFactory"  class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- com.syy.domain.Person  person-->
        <property name="typeAliasesPackage" value="com.syy.domain"/>
    </bean>
    <!-- IPersonDao.xml  IPersonDao.java-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
         <property name="basePackage" value="com.syy.dao"/>
         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

**TestDataSource **

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDataSource {
    private static final Logger log = Logger.getLogger(TestDataSource.class.getName());
    @Autowired
    IPersonDao dao;
    @Test
    public void test01() throws SQLException {
        List<Person> data = dao.findAll();
        System.out.println(data);
    }
    @Test
    public void test02() throws SQLException {
        Person p =  new Person("hello",200.00);
        dao.save(p);
    }
}

8 Spring整合MyBatis框架配置事务

applicationContext.xml


    <!--配置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:pointcut id="service" expression="execution(* com.syy.service.impl.*ServiceImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
    </aop:config>

TestPersonService

@Test
    public void test03(){
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("jack",100.00));
        personList.add(new Person("rose",200.00));
        personList.add(new Person("tony",300.00));
        personService.savePersons(personList);
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值