springmvc(三)之整合SSM

SSM整合说明

在这里插入图片描述
创建数据库

create database ssm;
use ssm;
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);

配置项目依赖
导入依赖jar包

搭建环境

编写实体类

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 +
                '}';
    }
}

编写dao接口

/**
 * 账户dao接口
 */
public interface IAccountDao {

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

    //保存账户信息
    public void saveAccount(Account account);
}

编写service接口和实现类

public interface IAccountService {
    //查询所有账户信息
    public List<Account> findAll();

    //保存账户信息
    public void saveAccount(Account account);
}
public class AccountServiceimpl implements IAccountService{
    @Override
    public List<Account> findAll() {
        System.out.println("业务层查询所有账户。。。");
        return null;
    }

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

    }
}

表现层实现类

/**
 * 账户web层
 */
public class AccountController {
}

搭建结构图

在这里插入图片描述

首先搭建spring层环境(spring只负责业务层和持久层,表现层有springMVC负责)

  1. 在ssm_web项目中resources下创建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.tju">
        <!--配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
    </context:component-scan>

</beans>

对AccountServiceimpl实现类上加上注解

@Service("accountService")
public class AccountServiceimpl implements IAccountService{
...
}

测试spring框架

public class TestSpring {

    @Test
    public void run1(){
     //加载spring配置文件
        ApplicationContext ac =new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
     //获取对象
        IAccountService as = (IAccountService)ac.getBean("accountService");

        //调用方法
        List<Account> all = as.findAll();
    }
}

搭建springmvc框架

配置web.xml

  1. 在web.xml中配置DispatcherServlet前端控制器
 <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>
  1. 在web.xml中配置DispatcherServlet过滤器解决中文乱码
<!--解决中文乱码的过滤器-->
  <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>

创建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注解,spring处理的service和dao,而springmvc处理controller-->
    <context:component-scan base-package="cn.tju">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
    </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 location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <!--开启SpringMVC注解支持-->
    <mvc:annotation-driven />
</beans>

测试SpringMVC的框架搭建是否成功

前端index.jsp

<a href="account/findAll">测试</a>

前端控制器

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


    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("表现层:查询所有信息");
        return "list";
    }
}

返回list.jsp

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

spring整合springmvc

问题:在AccountController表现层调用业务层的方法,首先要有业务层的对象,思路就是依赖注入
但启动Tomcat服务器不会加载spring的配置文件
解决方法:
原理图
在这里插入图片描述

spring整合springmvc,启动Tomcat服务器的时候需要加载spring的配置文件
ServletContext 域对象,服务器启动时创建ServletContext对象,服务器关闭才会销毁
一类监听器,监听ServletContext域对象创建和销毁的,执行一次,服务器启动执行
监听器去加载spring配置文件,创建web版本工厂,存储到ServletContext对象

在web.xml中配置spring的监听器
在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置
ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件
所以要添加路径配置

 <!--配置Spring的监听器,默认只加载application.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>

在controller中注入service对象,调用service对象的方法进行测试

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

    @Autowired
    private IAccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("表现层:查询所有信息执行了");
        //调用业务层service的方法,有service对象
        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:///ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="xgh961120"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入配置文件-->
    <mappers>
        <!--<mapper class="cn.tju.dao.IAccountDao"></mapper>-->
        <package name="cn.tju.dao"></package>
    </mappers>


</configuration>
  1. 在IAccountDao接口的方法上添加注解,编写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);
}
  1. 编写测试的方法
@Test
    public void run2 () throws Exception {
        Account account1 = new Account();
        account1.setName("qqq");
        account1.setMoney(400d);
        //加载mybatis配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //创建SqlSessiong对象
        SqlSession sqlSession = factory.openSession();
        //获取到代理对象
        IAccountDao dao = sqlSession.getMapper(IAccountDao.class);
        //保存
        dao.saveAccount(account1);
        //提交事务
        sqlSession.commit();
        //查询所有数据
        List<Account> list = dao.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
        //关闭资源
        sqlSession.close();
        in.close();


    }

SSM整合之spring整合Mybatis框架

目标:业务层service能调用到Dao对象
核心就是把生成Dao接口的代理对象存到容器中去,在service注入dao对象

在spring的配置文件applicationContext.xml中

  1. 目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中
 <!--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="xgh961120" />
    </bean>
    <!--配置SqlSessionFactory工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置IAccount接口所在包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.tju.dao"></property>
    </bean>
  1. 在AccountDao接口中添加@Repository注解
@Repository
public interface IAccountDao {
  1. 在service中注入dao对象,进行测试
@Service("accountService")
public class AccountServiceimpl implements IAccountService{

    @Autowired
    private IAccountDao accountDao;

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

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

    }
}

测试

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

    @Autowired
    private IAccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("表现层:查询所有信息执行了");
        //调用业务层service的方法,有service对象
        List<Account> list = accountService.findAll();
        model.addAttribute("list",list);

        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>
<h3>查询所有的账户信息</h3>
<c:forEach items="${list}" var="account">
    ${account.name}
</c:forEach>
</body>
</html>

结果图
在这里插入图片描述

配置Spring的声明式事务管理

<!--配置Spring框架声明式事务管理-->
<!--配置事务管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">

<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 pointcut="execution(* cn.tju.service.impl.*ServiceImpl.*(..))" advice-ref="txAdvice"/>
</aop:config>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值