SSM整合(XML+注解方式)

SSM整合

文章目录

  • SSM整合
  • 环境搭建
    • 1.创建数据库
    • 2.创建maven项目导入坐标
    • 3.编写实体类
    • 4.编写持久层接口
    • 5.编写业务层接口
    • 6.编写业务层实现类
  • 配置Spring
    • 1.编写spring配置文件并导入约束
    • 2.使用注解配置业务层和持久层
    • 3.测试spring是否能独立运行
  • 配置SpringMVC
    • 1.在web.xml里配置前端控制器(DispatchServlet)
    • 2.编写SpringMVC配置文件
    • 3.编写Controller和jsp页面
  • 整合Spring和SpringMVC
    • 1.配置监听器实现启动服务时创建容器(加载spring配置文件)即可
    • 2.测试
  • 配置Mybatis
    • 1. 在web项目中编写SqlMapConfig.xml的配置文件,编写核心配置文件
    • 2.在AccountDao接口的方法上添加注解,编写SQL语句
    • 3.测试
  • 整合Spring和Mybatis

环境搭建

1.创建数据库

ssm数据库-account表

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

2.创建maven项目导入坐标

<?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>com.yll</groupId>
    <artifactId>mySSM</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>mySSM 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.7</maven.compiler.source>
        <maven.compiler.target>1.7</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>
        <shiro.version>1.2.3</shiro.version>
        <mysql.version>8.0.16</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-context-support</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-orm</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-core</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-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</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>mySSM</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.1.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.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</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>

3.编写实体类

com.yll.domain.Account

package com.yll.domain;

import java.io.Serializable;

/**
 * 账户
 * */
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 +
                '}';
    }
}

4.编写持久层接口

dao层
com.yll.dao.IAccountDao

/**
 * 账户dao的接口
 * */
@Repository
public interface IAccountDao {
    //查询所有账户信息
    public List<Account> findAll();
    //保存账户
    public void saveAccount(Account account);
}

5.编写业务层接口

com.yll.service.AccountService

/**
 * account业务层
 * */
public interface AccountService {

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

6.编写业务层实现类

com.yll.service.impl.AccountService

public class AccountServiceImpl implements AccountService {

    private IAccountDao accountDao;
    @Override
    public List<Account> findAll() {
        System.out.println("业务层,查询所有账户");
        return null;
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层,保存账户");
    }
}

配置Spring

1.编写spring配置文件并导入约束

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: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">
    <!--开启注解扫描,只希望处理service 和dao,controller不需要处理-->
    <context:component-scan base-package="com.yll">
        <!--配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

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

业务层实现类

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private IAccountDao accountDao;
    @Override
    public List<Account> findAll() {
        System.out.println("业务层,查询所有账户");
        return accountDao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
        System.out.println("业务层,保存账户");
    }
}

持久层

/**
 * 账户dao的接口
 * */
@Repository
public interface IAccountDao {
    //查询所有账户信息
    @Select("select * from account")
    public List<Account> findAll();
    //保存账户
    @Insert("insert into account(name,money)values(#{name},#{money})")
    public void saveAccount(Account account);
}

3.测试spring是否能独立运行

public class testSpring {
    @Test
    public void testspring1(){
        //1.加载配置文件
        ApplicationContext ac =  new ClassPathXmlApplicationContext("applicationContext.xml");
        //2.获取对象
        AccountService as = (AccountService) ac.getBean("accountService");
        //3.
        as.findAll();
    }
}

配置SpringMVC

1.在web.xml里配置前端控制器(DispatchServlet)

<!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>

  <!--配置前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</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-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!--解决中文乱码的过滤器-->
  <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>/*
  

2.编写SpringMVC配置文件

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">

    <!--开启注解扫描,只扫描Controller-->
    <context:component-scan base-package="com.yll">
        <!--配置哪些注解扫描-->
        <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>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--过滤静态资源-->
    <mvc:resources mapping="/css/" location="/css/**"></mvc:resources>
    <mvc:resources mapping="/images/" location="/images/**"></mvc:resources>
    <mvc:resources mapping="/js/" location="/js/**"></mvc:resources>
    <!--开启SpringMVC注解的支持-->
    <mvc:annotation-driven/>
</beans>

3.编写Controller和jsp页面

index.jsp

//index.jsp
<a href="account/testfindAll">测试SpringMVC</a>

AccountController

/**
 * web层
 * */
@Controller
@RequestMapping("/account")
public class AccountController {

    @RequestMapping("/testfindAll")
    public String findAll(Model model){
        System.out.println("表现层…findALL…");
        return "list";
    }
}

整合Spring和SpringMVC

1.配置监听器实现启动服务时创建容器(加载spring配置文件)即可

在web.xml里面配置

  <!--配置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>

2.测试

  • 在controller中注入service对象,调用service对象的方法进行测试
/**
 * web层
 * */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/testfindAll")
    public String findAll(Model model){
        System.out.println("表现层…findALL…");
        //调用业务层方法
        accountService.findAll();
        return "list";
    }
}

配置Mybatis

1. 在web项目中编写SqlMapConfig.xml的配置文件,编写核心配置文件

<?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>
    <!--配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="52151"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射配置文件-->
    <mappers>
<!--        <mapper class="com.yll.dao.IAccountDao"></mapper>-->
        <package name="com.yll.dao"/>
    </mappers>
</configuration>

2.在AccountDao接口的方法上添加注解,编写SQL语句

/**
 * 账户dao的接口
 * */
public interface IAccountDao {
    //查询所有账户信息
    @Select("select * from account")
    public List<Account> findAll();
    //保存账户
    @Insert("insert into account(name,money)values(#{name},#{money})")
    public void saveAccount(Account account);
}

3.测试

   /**
     * 测试查询
     * */
    @Test
    public void test1() throws IOException {
        //加载配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //创建SqlSession对象
        SqlSession session = factory.openSession();
        //获取代理对象
        IAccountDao dao = session.getMapper(IAccountDao.class);
        //查询
        List<Account> accounts = dao.findAll();
        for(Account account:accounts){
            System.out.println(account);
        }
        //释放资源
        session.close();
        in.close();
    }
 /**
     * 测试保存
     * */
    @Test
    public void test2() throws IOException {
        //加载配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //创建SqlSession对象
        SqlSession session = factory.openSession();
        //获取代理对象
        IAccountDao dao = session.getMapper(IAccountDao.class);
        //查询
        Account account = new Account();
        account.setName("yll");
        account.setMoney(52151);
        dao.saveAccount(account);
        //提交事务
        session.commit();
        //释放资源
        session.close();
        in.close();
    }

整合Spring和Mybatis

  1. 目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中
 <!--Spring整合Mybatis框架-->
    <!--配置c3p0-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC"/>
        <property name="user" value="root"/>
        <property name="password" value="52151"/>
    </bean>
    <!--配置SqlSessionFactory工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置Dao接口所在的包 (创建代理对象)-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yll.dao"></property>
    </bean>
  1. 在AccountDao接口中添加@Repository注解
@Repository
public interface IAccountDao {
   .......
}
  1. 在service中注入dao对象,进行测试
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private IAccountDao accountDao;
    .......
  1. 在Controller访问其他层进行测试
    @Autowired
    private AccountService accountService;

    @RequestMapping("/testfindAll")
    public String findAll(Model model){
        System.out.println("表现层…findALL…");
        //调用业务层方法
        List<Account> accounts = accountService.findAll();
        for (Account account:accounts){
            System.out.println(account);
        }
        model.addAttribute("lists",accounts);
        return "list";
    }
  1. 配置Spring的声明式事务管理
  • 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:advisor advice-ref="txAdvice" pointcut="execution(* com.yll.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>
  • jsp代码
    <h3>测试保存</h3>
    <form method="post" action="account/saveAccount">
        姓名:<input type="text" name="name"/><br>
        金额:<input type="text" name="money"/><br>
        <input type="submit" value="提交">
    </form>
  • 利用Controller测试能不能走通
    @RequestMapping("/saveAccount")
    public void saveAccount(Account account, HttpServletResponse response, HttpServletRequest request) throws IOException {
        accountService.saveAccount(account);
        response.sendRedirect(request.getContextPath()+"/account/testfindAll");
        return ;
    }

你可能感兴趣的:(SSM)