整合需要的jar包和源码将在文末给出

本文参考黑马程序员视频,由于视频用的环境和我使用的环境不同,建议使用我的环境及jar包(比较新)

一 整合思路

第一步 整合dao层

mybatis和spring整合,通过spring管理mapper接口:使用mapper扫描器自动扫描mapper接口在spring中进行注册

第二部 整合service层

通过spring管理service接口

使用配置方式将service接口配置在spring配置文件中。

实现事务控制

第三步:整合spring'mvc

由于springmvc是spring的模块,不需要整合。

二 准备环境:

java环境:

mysql 5.5

本文的例子只使用到了items表,故给出items字段,可根据一下查询结果建表和插入数据

所有jar包将在文末给出

工程结构:

三 程序编写

1 整合dao(持久层)  mybatis和spring进行整合

mybatis全局配置文件 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>
    <!-- 配置mapper
        由于使用spring和mybatis整合后使用mapper扫描这里不需要配置。
        必须遵循:mapper.xml和maapper.java文件同名且在同一个目录
     -->
</configuration>

spring配置文件 applicationContext-dao.xml

配置:数据源,SqlSessionFactory mapper扫描器

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.2.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
         http://www.springframework.org/schema/task
         http://www.springframework.org/schema/task/spring-task-4.2.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

        <!-- 加载db.properties文件 -->
        <context:property-placeholder location="classpath:db.properties"/>  

        <!-- dbcp数据库连接池 -->
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
            <property name="maxActive" value="30"/>
            <property name="maxIdle" value="5"/>
        </bean>
        <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 数据库连接池 -->
            <property name="dataSource" ref="dataSource" />
            <!-- 加载mybatis的全局配置文件 -->
            <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
        </bean>

        <!-- mapper扫描器 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
             <property name="basePackage" value="pers.czs.ssm.mapper"></property>
             <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        </bean>
</beans>

定义po类Items.clss,ItemsCustom.class,ItemsQueryVo.class,其中ItemsCustom.class和ItemsQueryVo.class是Items.clss的扩展类,用于后面编写mapper.xml文件中的输入和输出映射

package pers.czs.ssm.po;

import java.util.Date;

public class Items {
    private int id;
    private String name;
    private float price;
    private String detail;
    private String pic;
    private Date createtime;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public String getDetail() {
        return detail;
    }
    public void setDetail(String detail) {
        this.detail = detail;
    }
    public String getPic() {
        return pic;
    }
    public void setPic(String pic) {
        this.pic = pic;
    }
    public Date getCreatetime() {
        return createtime;
    }
    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }
}
package pers.czs.ssm.po;

public class ItemsCustom extends Items{

}
package pers.czs.ssm.po;

public class ItemsQueryVo {
    private Items items;

    private ItemsCustom itemsCustom;

    public Items getItems() {
        return items;
    }

    public void setItems(Items items) {
        this.items = items;
    }

    public ItemsCustom getItemsCustom() {
        return itemsCustom;
    }

    public void setItemsCustom(ItemsCustom itemsCustom) {
        this.itemsCustom = itemsCustom;
    }

}

定义ItemsMapper.xmlItemsMapper.java

<?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="pers.czs.ssm.mapper.ItemsMapper">

    <!-- sql片段 -->
    <!-- 商品查询条件 -->
    <sql id="query_items_where">
        <if test="itemsCustom!=null">
            <if test="itemsCustom.name!=null and itemsCustom.name!=''">
                and items.name like '%${itemsCustom.name}%'
            </if>
        </if>
    </sql>

    <!-- 查询商品信息 -->
    <select id="findItemsList" parameterType="pers.czs.ssm.po.ItemsQueryVo"
            resultType="pers.czs.ssm.po.ItemsCustom">
        select * from items
        <where>
            <include refid="query_items_where"/>
        </where>
    </select>

</mapper>
package pers.czs.ssm.mapper;

import java.util.List;

import pers.czs.ssm.po.ItemsCustom;
import pers.czs.ssm.po.ItemsQueryVo;

public interface ItemsMapper {
    public List<ItemsCustom> findItemsList (ItemsQueryVo itemsQueryVo)throws Exception;
}

2 整合service(逻辑层) 让spring管理service接口

定义service接口ItemService 和接口实现类ItemServiceImpl

package pers.czs.ssm.service;

import java.util.List;

import pers.czs.ssm.po.ItemsCustom;
import pers.czs.ssm.po.ItemsQueryVo;

public interface ItemsService {
    public List<ItemsCustom> findItemsList (ItemsQueryVo itemsQueryVo)throws Exception;
}
package pers.czs.ssm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import pers.czs.ssm.mapper.ItemsMapper;
import pers.czs.ssm.po.ItemsCustom;
import pers.czs.ssm.po.ItemsQueryVo;
import pers.czs.ssm.service.ItemsService;

public class ItemsServiceImpl implements ItemsService{

    @Autowired
    private ItemsMapper itemsMapper;

    @Override
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
        // 通过ItemsMapper查询数据库
        return itemsMapper.findItemsList(itemsQueryVo);
    }
}

在spring容器配置service(applicationContext-service.xml)

创建applicationContext-service.xml,文件中配置service。

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.2.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
         http://www.springframework.org/schema/task
         http://www.springframework.org/schema/task/spring-task-4.2.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

         <!-- 商品管理service -->
        <bean id="itemsService" class="pers.czs.ssm.service.impl.ItemsServiceImpl"></bean>
</beans>

事务控制 (applicationContext-transaction.xml)

applicationContext-transaction.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.2.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
         http://www.springframework.org/schema/task
         http://www.springframework.org/schema/task/spring-task-4.2.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

         <!-- 事务管理器 -->
        <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="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
          </tx:attributes>
        </tx:advice>

        <!-- 切面 -->
        <aop:config>
          <aop:advisor advice-ref="txAdvice"
          pointcut="execution(* pers.czs.ssm.service.impl.*.*(..))"/>
        </aop:config>
</beans>

3 整合springmvc

创建springmvc.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.2.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
         http://www.springframework.org/schema/task
         http://www.springframework.org/schema/task/spring-task-4.2.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

         <!-- 扫描controller注解,多个包中间使用半角逗号分隔 -->
    <context:component-scan base-package="pers.czs.ssm.controller"/>
    <!--注解映射器 -->
    <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
    <!--注解适配器 -->
    <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->

    <!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置
    mvc:annotation-driven默认加载很多的参数绑定方法,
    比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
    实际开发时使用mvc:annotation-driven
     -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- ViewResolver -->
    <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

配置前端控制器以及加载spring容器(都是在web.xml内配置的,这里我直接给出web.xml文件代码)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>springmvc_mybatis</display-name>

  <!-- 加载spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
    </context-param>
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

  <!-- springmvc的前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-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>

编写ItemsController(就是Handler)

package pers.czs.ssm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import pers.czs.ssm.po.ItemsCustom;
import pers.czs.ssm.service.ItemsService;

@Controller
public class ItemsController {

    @Autowired
    private ItemsService itemsService;

    @RequestMapping("/queryItems")
    public ModelAndView queryItems() throws Exception {
        // 调用service查找 数据库,查询商品列表
        List<ItemsCustom> itemsList = itemsService.findItemsList(null);

        //返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        //相当 于request的setAttribut,在jsp页面中通过itemsList取数据
        modelAndView.addObject("itemsList",itemsList);

        //指定视图,没有配置前缀后缀
        //modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");

        //指定视图,在视图解析器中配置了前缀后缀后可以省略一些东西
        modelAndView.setViewName("items/itemsList");

        return modelAndView;
    }

}

编写itemsList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!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>
<form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
    <td>商品名称</td>
    <td>商品价格</td>
    <td>生产日期</td>
    <td>商品描述</td>
    <td>操作</td>
</tr>
<c:forEach items="${itemsList }" var="item">
<tr>
    <td>${item.name }</td>
    <td>${item.price }</td>
    <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
    <td>${item.detail }</td>

    <td><a href="${pageContext.request.contextPath }/item/editItem.action?id=${item.id}">修改</a></td>

</tr>
</c:forEach>

</table>
</form>
</body>

</html>

浏览器输入http://localhost:8080/springmvc_mybatis/queryItems.action访问

查询成功

四 jar包及源码

链接:https://pan.baidu.com/s/16yTiEsCj8ejmh0gm8KHn8A
提取码:hegb

SSM整合的简单实现的更多相关文章

  1. SSM整合之---简单选课系统

    简单选课系统 一.实体图 二.功能 三.代码实现 1.SSM环境搭建 (1)pom.xml <dependencies> <dependency> <groupId> ...

  2. SpringMVC之简单的增删改查示例(SSM整合)

    本篇文章主要介绍了SpringMVC之简单的增删改查示例(SSM整合),这个例子是基于SpringMVC+Spring+Mybatis实现的.有兴趣的可以了解一下. 虽然已经在做关于SpringMVC ...

  3. ssm 整合 redis(简单教程)

    最后我建议大家使用 Spring StringRedisTemplate 配置,参阅: http://blog.csdn.net/hanjun0612/article/details/78131333 ...

  4. SSM整合配置

    SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis) 使用SSM(Spring.SpringMVC和Mybatis)已经有三个多月了,项目在技术上已经没有什么难点了,基于现有 ...

  5. 04.redis集群+SSM整合使用

    redis集群+SSM整合使用 首先是创建redis-cluster文件夹: 因为redis最少需要6个节点(三主三从),为了更好的理解,我这里创建了两台虚拟机(192.168.0.109 192.1 ...

  6. spring MVC框架入门(外加SSM整合)

    spring MVC框架 一.什么是sping MVC Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面.Spring 框架提供了构建 W ...

  7. SpringMVC笔记——SSM框架搭建简单实例

    落叶枫桥 博客园 首页 新随笔 联系 订阅 管理 SpringMVC笔记——SSM框架搭建简单实例 简介 Spring+SpringMVC+MyBatis框架(SSM)是比较热门的中小型企业级项目开发 ...

  8. SSM框架的简单搭建

    转:https://blog.csdn.net/zhshulin/article/details/37956105 Spring+SpringMVC+MyBatis spring       : 4. ...

  9. SSM整合文档

    SSM整合文档 v2 一. 文件说明 文件名 描述 spring-servlet.xml 配置SpringMvc框架相关 applicationContext.xml 配置Spring容器 sprin ...

随机推荐

  1. 洛谷 P2147 [SDOI2008]洞穴勘测 (线段树分治)

    题目链接 题解 早就想写线段树分治的题了. 对于每条边,它存在于一段时间 我们按时间来搞 我们可把一条边看做一条线段 我们可以模拟线段树操作,不断分治下去 把覆盖\(l-r\)这段时间的线段筛选出来, ...

  2. Trailing Loves (or L'oeufs?)

    The number "zero" is called "love" (or "l'oeuf" to be precise, literal ...

  3. 关于strcmp函数的用法

    strcmp函数是在string.h库下的han函数, 具体用法如下: strcmp函数是用来比较2个字符串的函数,如srcmp(字如果符串1,字符串2),从第一个字符开始比较,如果到最后两个字符串完 ...

  4. C# 关于时区的操作

    有关时区自动更新的 在注册表以下路径,start键值3,4表示自动/不自动更新 计算机\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\tza ...

  5. Oracle分析函数系列之first_value/last_value:在记录集中查找第一条记录和最后一条记录

    [转自] http://blog.csdn.net/rfb0204421/article/details/7675911 注意:与max,min的区别,虽然也可以实现,但只是针对数字字段. 1.初始化 ...

  6. JS调用百度地图。

    必要条件:先注册百度开发者账号,然后申请调用地图的密钥(AK). 测试demo: 说明:百度开发平台上有很多demo,如下图:

  7. PIE 支持项目介绍

    目前PIE SDK已经支持了气象.海洋.农业.水利.测绘等多个行业应用. [气象应用-和WebGIS程序界面结合] [气象应用-积雪监测] [气象应用-洪涝监测] [气象应用-专题模板] [气象应用- ...

  8. PIE SDK矢量数据编辑事件的监听

    1.功能简介 通过IEditEvents接口,开发者可以监听到Editor对象的相关的事件,并且做出反应.包括Editor中开始编辑.结束编辑等操作,下面对矢量数据的编辑事件的监听功能进行介绍. 2. ...

  9. AWS and OpenStack

    AWS OpenStack EC2 Nova EBS Cinder EFS Manila S3 Swift Storage Gateway 本地上云 ClondFront 内容发布服务 VPC Neu ...

  10. 02-使用注解配置spring

    1 准备工作 1.导包 4+2+spring-aop[新版本需要导入 spring-aop 包] 2.为主配置文件引入新的命名空间(约束) [context] 3.开启使用注解代理配置文件 4.在类中 ...