Spring MVC入门第2天--Spring、SpringMVC与MyBatis三大框架整合

来源:互联网 发布:漆黑的特快列车 知乎 编辑:程序博客网 时间:2024/05/23 13:25
文档版本 开发工具 测试平台 工程名字 日期 作者 备注 V1.0 2016.07.01 lutianfei none

springmvc和mybatis整合

  • 需求: 使用springmvc和mybatis完成商品列表查询。

整合思路

  • spring+springmvc+mybaits的系统架构:

第一步:整合dao层

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

第二步:整合service层

  • 通过spring管理 service接口。
    • 使用配置方式将service接口配置在spring配置文件中。
    • 实现事务控制。

第三步:整合springmvc

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

商品列表查询案例

  • 准备环境
    • springmvc版本:spring3.2
  • 所需要的jar包:

    • 数据库驱动包:mysql5.1
    • mybatis的jar包
    • mybatis和spring整合包
    • log4j包
    • dbcp数据库连接池包
    • spring3.2所有jar包
    • jstl包
  • 参考: springmvc和mybatis整合

  • 工程结构:


整合dao

  • 目标:mybatis和spring进行整合。

  • 配置sqlMapConfig.xml mybatis自己的配置文件。

    • 全局setting配置,根据情况添加
    • 配置别名:用于批量扫描
    • 配置mapper:由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。但必须遵循:mapper.xml和mapper.java文件同名且在一个目录

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- 全局setting配置,根据需要添加 -->    <!-- 配置别名 -->    <typeAliases>        <!-- 批量扫描别名 -->        <package name="cn.itcast.ssm.po"/>    </typeAliases>    <!-- 配置mapper    由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。    必须遵循:mapper.xml和mapper.java文件同名且在一个目录      -->    <!-- <mappers>    </mappers> --></configuration>


  • 配置applicationContext-dao.xml
  • 配置内容:
    • 数据源
    • SqlSessionFactory
    • mapper扫描器

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"    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-3.2.xsd         http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.2.xsd         http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">    <!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->    <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>    <!-- sqlSessionFactory -->    <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="cn.itcast.ssm.mapper"></property>        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />    </bean></beans>


逆向工程生成po类及mapper(单表增删改查)

  • 将生成的文件拷贝至工程中。

手动定义商品查询mapper

  • 针对综合查询mapper,一般情况会有关联查询,建议自定义mapper
自定义ItemsMapperCustom.xml
  • sql语句:
    • SELECT * FROM items WHERE items.name LIKE ‘%笔记本%’
  • 注意: parameterType应传入包装对象(包装了一层pojo),定义ItemsQueryVo包装对象。包装商品信息相关的数据作为查询条件。
    • 为了系统的可扩展性,对原始生成的po进行扩展
    • 定义ItemsCustom类,即商品信息的扩展类。对原始的Items类中的信息进行扩展。
    • resultType同样也建议使用扩展对象。
  • 为了解决sql语句中的硬编码问题,建议使用动态sql
  • 为了查询功能的扩展引入sql片段

  • ItemsQueryVo.java

public class ItemsQueryVo {    //商品信息    private Items items;    //为了系统 可扩展性,对原始生成的po进行扩展    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;    }}


自定义:ItemsMapperCustom.java


整合service

  • 目标:让spring管理service接口。
定义service接口
  • 在ssm.service包下定义ItemsService接口

  • 在ssm.service.Impl包下定义ItemsServiceImpl类

    • 因为在applicationContext-dao.xml中已经使用了mapper扫描器,这里可以直接通过注解的方式将itemsMapperCustom自动注入。

在spring容器配置service

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

实现事务控制

  • 在applicationContext-transaction.xml中使用spring声明式事务控制方法。
  • 对mybatis操作数据库事物控制,spring使用jdbc的事物控制类,即DatSourceTransactionManager
  • 因为操作了数据库需要事物控制,所以需要配置数据源

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"    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-3.2.xsd         http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.2.xsd         http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "><!-- 事务管理器     对mybatis操作数据库事务控制,spring使用jdbc的事务控制类--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <!-- 数据源    dataSource在applicationContext-dao.xml中配置了     -->    <property name="dataSource" ref="dataSource"/></bean><!-- 通知 --><tx:advice id="txAdvice" transaction-manager="transactionManager">    <tx:attributes>        <!-- 传播行为 -->        <tx:method name="save*" propagation="REQUIRED"/>        <tx:method name="delete*" propagation="REQUIRED"/>        <tx:method name="insert*" 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:method name="select*" propagation="SUPPORTS" read-only="true"/>    </tx:attributes></tx:advice><!-- aop --><aop:config>    <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.ssm.service.impl.*.*(..))"/></aop:config></beans>


整合springmvc

  • 创建springmvc.xml文件,配置处理器映射器适配器视图解析器
    <context:component-scan base-package="cn.itcast.ssm.controller"></context:component-scan>    <!-- 使用 mvc:annotation-driven 加载注解映射器和注解适配器配置-->    <mvc:annotation-driven></mvc:annotation-driven>    <!-- 视图解析器 解析jsp解析,默认使用jstl标签,classpath下的得有jstl的包     -->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <!-- 配置jsp路径的前缀 -->        <property name="prefix" value="/WEB-INF/jsp/"/>        <!-- 配置jsp路径的后缀 -->        <property name="suffix" value=".jsp"/>    </bean>


配置前端控制器

  • web.xml中加入如下内容。
<!-- springmvc前端控制器 -->    <servlet>        <servlet-name>springmvc</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:spring/springmvc.xml</param-value>        </init-param>    </servlet>    <servlet-mapping>        <servlet-name>springmvc</servlet-name>        <!-- 第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析 第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析             使用此种方式可以实现 RESTful风格的url 第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时, 仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。 -->        <url-pattern>*.action</url-pattern>    </servlet-mapping>


编写Controller(就是Handler)

@Controller//为了对url进行分类管理 ,可以在这里定义根路径,最终访问url是根路径+子路径//比如:商品列表:/items/queryItems.action@RequestMapping("/items")public class ItemsController {    @Autowired    private ItemsService itemsService;    // 商品查询    @RequestMapping("/queryItems")    public ModelAndView queryItems(HttpServletRequest request) throws Exception {        //测试forward后request是否可以共享        System.out.println(request.getParameter("id"));        // 调用service查找 数据库,查询商品列表        List<ItemsCustom> itemsList = itemsService.findItemsList(null);        // 返回ModelAndView        ModelAndView modelAndView = new ModelAndView();        // 相当 于request的setAttribut,在jsp页面中通过itemsList取数据        modelAndView.addObject("itemsList", itemsList);        // 指定视图        // 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为        // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");        // 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀        modelAndView.setViewName("items/itemsList");        return modelAndView;    }


编写jsp

  • 编写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 }/items/editItems.action?id=${item.id}">修改</a></td></tr></c:forEach></table></form></body></html>


加载spring容器

  • 将mapper、service、controller加载到spring容器中。

  • 建议使用通配符加载上边的配置文件。

    • web.xml中,添加spring容器监听器,加载spring容器。
  • 测试访问 : http://localhost/ssm_1/items/queryItems.action

1 0
原创粉丝点击