ssm整合

1.创建数据库和表结构

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

2.创建Maven工程

3.导入坐标并配置依赖

<?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>
      <shiro.version>1.2.3</shiro.version>
      <mysql.version>5.1.6</mysql.version>
      <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>

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

4.编写实体类

在source root(java)下创建cn.itcast.domain创建实体类:
package cn.itcast.domain;

import java.io.Serializable;

/**

  • 账户信息
    */
    public class Accout 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;
    }
    }

5.编写持久层接口

在source root下创建cn.itcast.dao编写持久层接口:

package cn.itcast.dao;

import cn.itcast.domain.Accout;

import java.util.List;

/**
 * 账户接口
 */
public interface AccoutDao {

    //查询所有账户信息
    public List<Accout> findAll();

    //保存账户信息
    public void saveAccout(Accout accout);
}

6. 业务层接口及业务层接口实现类

在source root下创建cn.itcast.service编写业务层接口:

package cn.itcast.service;

import cn.itcast.domain.Accout;

import java.util.List;

public interface AccountService {

    //查询所有账户信息
    public List<Accout> findAll();

    //保存账户信息
    public void saveAccout(Accout accout);

}

在source root下创建cn.itcast.service.impl编写业务层接口实现类:

package cn.itcast.service.impl;

import cn.itcast.domain.Accout;
import cn.itcast.service.AccountService;
import org.springframework.stereotype.Service;

import java.util.List;

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

    public List<Accout> findAll() {
        System.out.println("业务层:查询所有账户。。。");
        return null;
    }

    public void saveAccout(Accout accout) {
        System.out.println("业务层:保存账户。。。");
    }
}

此时,整合环境已经搭建完成。接下来进行spring的配置。
其中@Service必须标记在实现类上,@Service服务层组件,用于标注业务层组件,表示定义一个bean,自动根据bean的类名实例化一个首写字母为小写的bean,@Service是把spring容器中的bean进行实例化,也就是等同于new操作,只有实现类是可以进行new实例化的,而接口则不能。参考链接:@service注解

7. 配置spring

在resources root(resource)下创建applicationContext.xml文件,填写具体的配置信息,并开启注解的扫描,希望处理source root下的service和dao中的注解,其中controller(属于springmvc)不需要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: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和dao,controller不需要Spring框架去处理-->
    <context:component-scan base-package="cn.itcast">
        <!--配置哪些注解不扫描,annotation表示注解,-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

关于spring注解的扫描主要有:
@Component 泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Service 用于标注业务层组件
@Controller 用于标注控制层组件(如srping mvc的controller,struts中的action)
@Repository 用于标注数据访问组件,即DAO组件
参考链接:详解spring applicationContext.xml 配置文件

8.对spring进行测试

在source root下创建cn.itcast.test,创建测试类TestSpring:

package cn.itcast.test;
import cn.itcast.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
    @Test//属于junit依赖
    public void run1(){
        //  加载配置文件,即resources中的applicationContext.xml文件,获取核心容器对象(ioc)
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        //  根据id获取Bean对象,即java.cn.itcast.service.impl.AccountServiceImpl中的@Service("accountService")注解
        AccountService as = (AccountService) ac.getBean("accountService");
        //  调用其中的findAll()方法
        as.findAll();
    }
}

右键run1,得到
业务层:查询所有账户。。
说明spring搭建成功。
在之前,需要在resources中添加log4j.properties配置文件。
关于@Test相关信息 ,参考:@Test
到此,spring的开发环境搭建完成,接下来搭建springmvc框架环境。

9. 搭建springmvc框架

9.1. 设计请求页面

在webapp中删除并新建index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2021/3/6
  Time: 10:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--account表示类的注解,findAll表示方法的注解--%>
    <a href="account/findAll">测试</a>

</body>
</html>

9.2.在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>
    <!--配置前端控制器,设计名为dispatcherServlet的servlet前端控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加载springmvc.xml配置文件,即resources中的springmvc.xml。即设计控制范围-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--启动服务器,创建该servlet-->
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--解决中文乱码的过滤器,设计名为characterEncodingFilter的filter过滤器-->
    <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-->
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!--拦截内容,/*表示什么都拦截-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

由于其中

<!--加载springmvc.xml配置文件,即resources中的springmvc.xml。即设计控制范围-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>

指定了配置文件为springmvc.xml,所以设计springmvc配置文件。

9.3.设计springmvc配置文件

在resource root中创建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注解,即java下的cn.itcast.controller包-->
    <context:component-scan base-package="cn.itcast">
        <!--org.springframework.stereotype.Controller对应@Controller层-->
        <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>

    <!--过滤静态资源-->
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>

    <!--开启Springmvc注解的支持-->
    <mvc:annotation-driven/>
</beans>

由于在springmvc.xml中设计了

        <!--org.springframework.stereotype.Controller对应@Controller层-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

表示只扫描Controller下的注解,而controller注解出现在source root下的cn.itcast.controller.AccountController文件中,所以要在该文件下添加account/findAll的注解,用于响应页面请求:

9.4.设计AccountController文件

package cn.itcast.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 账户web
 */
@Controller
@RequestMapping("/account")
public class AccountController {
    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("表现层,查询所有的账户信息。。。");
        //注意,这个返回的list会在视图管理器管理的页面中会有一个对应的list.jsp
        return "list";
    }
}

此时,当请求页面发送请求时,会调用该页面下的findAll()方法,该方法运行后会返回list,而list会在视图管理器管理的页面中会有一个对应的list.jsp文件,作为返回界面,因此需要设计list.jsp文件:

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2021/3/6
  Time: 10:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <h3>查询了所有的账户信息</h3>

</body>
</html>

9.5.配置Tomcat

运行Tomcat,发送请求即可。

10.创建spring整合springmvc的框架

思路
想要spring整合springmvc,即当运行tomcat时springmvc能够调用spring中的方法即可。
由于启动Tomcat->创建web.xml中的Servlet->加载springmvc.xml->只扫描*@Controller* 注解,从头到尾都没有加载source root中的cn.itcast.service.impl中的*@Service* 注解,所以我们需要使用监听器,监听器也是在Tomcat服务器运行的时候启动的,即启动Tomcat->创建监听器Listener->加载applicationContext.xml->扫描*@Service*注解。如此一来,便将spring和springmvc中的注解同时扫描了,之后就在控制器中调用即可。

10.1.在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>
    <!--配置spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml(该文件在resource root目录下)-->
    <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>

    <!--配置前端控制器,设计名为dispatcherServlet的servlet前端控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加载springmvc.xml配置文件,即resources中的springmvc.xml。即设计控制范围-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--启动服务器,创建该servlet-->
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--解决中文乱码的过滤器,设计名为characterEncodingFilter的filter过滤器-->
    <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-->
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!--拦截内容,/*表示什么都拦截-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

注意,监听器要配置监听文件的位置:

<!--设置配置文件的路径-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

10.2.在AccountController注入service对象,调用service对象方法

package cn.itcast.controller;

import cn.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

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

    @Autowired//按类型注入
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("表现层,查询所有的账户信息。。。");
        //调用service的方法(业务层)
        accountService.findAll();
        //注意,这个返回的list会在视图管理器管理的页面中会有一个对应的list.jsp
        return "list";
    }

}

启动Tomcat测试即可,print:

表现层,查询所有的账户信息。。。
业务层:查询所有账户。。。

11. spring整合Mybatis框架

写到这发现前面的account拼错了,现在全部改正。
运行时报了以下错误,我心一凉,以为不能改,后来发现是配置mybatis时字母打错了,所以遇事不要慌,仔细检查一遍,确认没问题/不会后->百度。参考链接如下:NullPointerException

org.apache.ibatis.exceptions.PersistenceException:  ### Error opening session.  Cause: java.lang.NullPointerException ### Cause: java.lang.NullPointerException

11.1搭建MyBatis框架

11.1.1在source root下的cn.itcast.dao.AccountDao持久层接口添加注解,并填写sql语句

package cn.itcast.dao;

import cn.itcast.domain.Account;
import cn.itcast.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

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

11.1.2. 在resource root下创建连接数据库的配置文件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"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射配置文件-->
    <mappers>
        <!--具体:<mapper class="cn.itcast.dao.AccountDao"/>-->
        <package name="cn.itcast.dao"/>
    </mappers>
</configuration>

11.1.3. 在source root 下的cn.itcast.test编写MyBatis的测试文件TestMyBatis.java

package cn.itcast.test;

import cn.itcast.dao.AccountDao;
import cn.itcast.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMyBatis {
    @Test
    public void run1() throws Exception {
        //加载配置文件(将内容放在一个Configuration类中)
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //(SqlSessionFactoryBuilder会读取Configuration类中信息进而)创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //SqlSessionFactory创建SqlSession对象
        SqlSession session = factory.openSession();
        //SqlSession获取到代理对象
        AccountDao dao = session.getMapper(AccountDao.class);
        //查询所有账户信息
        List<Account> list = dao.findAll();
        for(Account account:list){
            System.out.println(account);
        }
        //关闭资源
        session.close();
        in.close();
    }
}

运行run1()函数,得到:

Account{id=1, name='xxx', money=111.0}
Account{id=2, name='aaa', money=222.0}

说明MyBatis部署成功。

11.1.4. 在source root 下的cn.itcast.test.TestMyBatis.java编写测试MyBatis的Save方法

package cn.itcast.test;
import cn.itcast.dao.AccountDao;
import cn.itcast.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestMyBatis {

    /**
     * 测试查询
     * @throws Exception
     */
    @Test
    public void run1() throws Exception {
        //加载配置文件(将内容放在一个Configuration类中)
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //(SqlSessionFactoryBuilder会读取Configuration类中信息进而)创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //SqlSessionFactory创建SqlSession对象
        SqlSession session = factory.openSession();
        //SqlSession获取到代理对象
        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);
        //加载配置文件,将内容放在Configuration类中
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //SqlSessionFactoryBuilder读取Configuration类中的信息创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //SqlSessionFactory创建SqlSession对象
        SqlSession session = factory.openSession();
        //获取到代理对象,它获取对应的Mapper,让映射器通过命名空间
        // 和方法名称找到对应的SQL,发送给数据库执行后返回结果
        AccountDao dao = session.getMapper(AccountDao.class);
        //保存
        dao.saveAccount(account);
        //提交事务
        session.commit();
        //关闭资源
        session.close();
        in.close();
    }
}

运行run()2即可,刷新数据得到新的一行数据。说明save方法也能使用。

11.2 整合Spring和MyBatis

使用 MyBatis 的主要 Java 接口就是 SqlSession。你可以通过这个接口来执行命令,获取映射器示例和管理事务。在介绍 SqlSession 接口之前,我们先来了解如何获取一个 SqlSession 实例。SqlSessions 是由 SqlSessionFactory 实例创建的。SqlSessionFactory 对象包含创建 SqlSession 实例的各种方法。而 SqlSessionFactory 本身是由 SqlSessionFactoryBuilder 创建的,它可以从 XML、注解或 Java 配置代码来创建 SqlSessionFactory。(Mybatis 读取XML配置文件后会将内容放在一个Configuration类中,SqlSessionFactoryBuilder会读取Configuration类中信息创建SqlSessionFactory。SqlSessionFactory创建SqlSession)
点击超链接,发送请求->AccountController调用accountService方法(由于调用Service,因此运行AccountServiceImpl类(AccountServiceImpl类中注入AccountDao接口,因此运行dao中的查找和保存操作),),可以对集合进行遍历或者储存操作,存储结束后,跳转list.jsp页面->在list.jsp页面遍历所查询的账户信息。
**

即在springmvc的控制器/实现类中注入spring业务层(service)接口,而在spring业务层实现类中注入MyBatis持久层(Dao)接口,而MyBatis持久层接口添加@Repository注解,使其可以被spring扫描。

**

  springmvc的控制器  private AccountService accountService;
  spring业务层实现类  private AccountDao accountDao;

11.2.1在spring配置文件中编写MyBatis配置信息

在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和dao,controller不需要Spring框架去处理-->
    <context:component-scan base-package="cn.itcast">
        <!--配置哪些注解不扫描,annotation表示注解,-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!--Spring整合MyBatis框架-->
    <!--配置连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--配置SqlSessionFactory工厂,因为工厂能够创建Session,有了Session才能获得代理对象-->
    <!--SqlSessionFactoryBean是专门用于整合spring和mvc存在的类,这个类可以通过连接池构建工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置AccountDao接口所在的包,生成这些接口的代理,将其传到容器中去-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.itcast.dao"/>
    </bean>
</beans>

11.2.2 在service实现类中注入dao接口(在spring实现类中注入Mybatis接口)

package cn.itcast.service.impl;
import cn.itcast.dao.AccountDao;
import cn.itcast.domain.Account;
import cn.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    //注入AccountDao接口
    @Autowired
    private AccountDao accountDao;

    public List<Account> findAll() {
        System.out.println("业务层:查询所有账户。。。");
        return accountDao.findAll();
    }
    public void saveAccout(Account account) {
        System.out.println("业务层:保存账户。。。");
        accountDao.saveAccount(account);
    }
}

11.2.3在AccountDao中添加@Repository注解,使其被spring扫描

package cn.itcast.dao;

import cn.itcast.domain.Account;
import cn.itcast.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * 账户接口
 */
//@Repository用于将数据访问层 (DAO 层 ) 的类标识为 Spring Bean
@Repository
public interface AccountDao {
    //查询所有账户信息
    @Select("select * from account")
    public List<Account> findAll();
    //保存账户信息,#{name}表示从accout取值
    @Insert("insert into account (name,money) values (#{name},#{money})")
    public void saveAccount(Account account);
}

11.2.4在AccountController中注入AccountService

由于AccountService中注入了dao中的接口,所以可以操作数据库了。

package cn.itcast.controller;

import cn.itcast.domain.Account;
import cn.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

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

    @Autowired//按类型注入AccountService
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("表现层,查询所有的账户信息。。。");
        //调用service的方法(业务层)
        List<Account> list = accountService.findAll();
        //将list进行储存
        model.addAttribute("list",list);
        //注意,这个返回的list会在视图管理器管理的页面中会有一个对应的list.jsp
        return "list";
    }
}

11.2.5设计转接页面list.jsp

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2021/3/6
  Time: 10:50
  To change this template use File | Settings | File Templates.
--%>
<%@ 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>

    <h3>查询了所有的账户信息</h3>

    <c:forEach items="${list}" var="account">
        ${account.name}

    </c:forEach>

</body>
</html>

其中jstl/core:forEach表示输出内容

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

运行Tomcat服务器,得到

查询了所有的账户信息
xxxaaa 大王大王熊大大王 

说明spring整合springmvc成功。

12. spring整合mybatis框架配置事务(Spring的声明式事务管理)

spring整合mybatis框架配置事务(Spring的声明式事务管理)
声明式事务管理即在spring中进行事务管理

12.1在applicationContext.xml配置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: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和dao,controller不需要Spring框架去处理-->
    <context:component-scan base-package="cn.itcast">
        <!--配置哪些注解不扫描,annotation表示注解,-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!--Spring整合MyBatis框架-->
    <!--配置连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--配置SqlSessionFactory工厂,因为工厂能够创建Session,有了Session才能获得代理对象-->
    <!--SqlSessionFactoryBean是专门用于整合spring和mvc存在的类,这个类可以通过连接池构建工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置AccountDao接口所在的包,生成这些接口的代理,将其传到容器中去-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.itcast.dao"/>
    </bean>
    <!--配置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>
</beans>

表示对service中的saveAccount方法进行了事务管理,

12.2 在请求页面设计一个表单

<%--
  Created by IntelliJ IDEA.
  User: 86187
  Date: 2021/3/6
  Time: 10:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--account表示类的注解,findAll表示方法的注解--%>
    <a href="account/findAll">测试查询</a>

    <h3>测试包</h3>

    <form action="account/save" method="post">
        姓名:<input type="text" name="name"/><br/>
        金额:<input type="text" name="money"/><br/>
        <input type="submit" value="保存"/><<br/>
    </form>
</body>
</html>

由于action=“account/save”,所以在控制器中设计save函数,

12.3在控制器设计保存函数

package cn.itcast.controller;

import cn.itcast.domain.Account;
import cn.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 账户web
 */
@Controller
@RequestMapping("/account")
public class AccountController {
    //按类型注入AccountService
    @Autowired
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("表现层,查询所有的账户信息。。。");
        //调用service的方法(业务层)
        List<Account> list = accountService.findAll();
        //将list进行储存
        model.addAttribute("list",list);
        //注意,这个返回的list会在视图管理器管理的页面中会有一个对应的list.jsp
        return "list";
    }

    /**
     * 保存
     * @return
     */
    @RequestMapping("/save")
    public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
        accountService.saveAccout(account);
        //重定向,    response.sendRedirect(request.getContextPath()+"/account/findAll");
        //注意,这个返回的list会在视图管理器管理的页面中会有一个对应的list.jsp
        return;
    }
}

其中运用了页面的重定向,首先定义请求和响应HttpServletRequest request, HttpServletResponse response,其次对响应重定向到另一个界面。
运行Tomcat即可。
发现报错:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)

查找原因是bean没有注入成功,网上说要检查注解是否正确,我检查无误后,发现是pom文件少填一个依赖,所以导致错误,把依赖添加,运行成功。

<dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.6.8</version>
      </dependency>

参考链接:ssm整合

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值