• SpringMVC由浅入深day01_8springmvc和mybatis整合


    springmvc和mybatis整合

    为了更好的学习 springmvc和mybatis整合开发的方法,需要将springmvc和mybatis进行整合。

    整合目标:控制层采用springmvc、持久层使用mybatis实现。

      8.1 需求

    使用springmvc和mybatis完成商品列表查询。

      8.2 整合思路

    springmvc+mybaits的系统架构:

    第一步:整合dao层

      mybatis和spring整合,通过spring管理mapper接口。

      使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

    第二步:整合service层

      通过spring管理 service接口。

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

      实现事务控制。

    第三步:整合springmvc

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

      8.3 准备环境

    数据库环境:mysql5.1

    java环境:

    jdk1.7.0_72

    eclipse indigo

    springmvc版本:spring3.2

    所需要的jar包:

    包括:spring(包括springmvc)、mybatis、mybatis-spring整合包、数据库驱动、第三方连接池。

    参考:“mybatis与springmvc整合全部jar包”目录

    数据库驱动包:mysql5.1

    mybatis的jar包

    mybatis和spring整合包

    log4j包

    dbcp数据库连接池包

    spring3.2所有jar包

    jstl包

    参考:

    工程结构:

      8.4 整合dao

    目标:

    1、spring管理SqlSessionFactory、mapper

    详细参考mybatis教程与spring整合章节。

        8.4.1 db.properties

    jdbc.driver=com.mysql.jdbc.Driver

    jdbc.url=jdbc:mysql://localhost:3306/mybatis

    jdbc.username=XXXX

    jdbc.password=XXXX

        8.4.2 log4j.properties

    # Global logging configuration,建议开发环境中要用debug

    log4j.rootLogger=DEBUG, stdout

    # Console output...

    log4j.appender.stdout=org.apache.log4j.ConsoleAppender

    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

        8.4.3 sqlMapConfig.xml

    mybatis自己的配置文件。

    在classpath下创建mybatis/sqlMapConfig.xml

        8.4.4 applicationContext-dao.xml

    配置数据源事务管理SqlSessionFactorymapper扫描器

    <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 ">
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 数据库连接池 -->
    <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="cn.itcast.springmvc.mapper"></property>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        </bean>
    </beans>

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

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

        8.4.6 手动定义商品查询mapper

    针对综合查询mapper,一般情况会有关联查询,建议自定义mapper

          8.4.6.1 ItemsMapperCustom.xml

    sql语句:

    SELECT * FROM items  WHERE items.name LIKE '%笔记本%'

          8.4.6.2 ItemsMapperCustom.java

      8.5 整合service

    让spring管理service接口对Service进行事务控制。

        8.5.1 定义service接口

    实现类

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

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

        8.5.3 事务控制(applicationContext-transaction.xml)

    在applicationContext-transaction.xml中使用spring声明式事务控制方法。

    <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 ">
    
    <!-- 事务管理器 -->
    <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>

      8.6 整合springmvc

        8.6.1 springmvc.xml

    创建springmvc.xml文件,配置处理器映射器、适配器、视图解析器。

    <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 ">
        
        <!-- 可以扫描controller、service、...
            这里让扫描controller,指定controller的包
         -->
        <context:component-scan base-package="cn.itcast.ssm.controller"></context:component-scan>
        
        <!--注解映射器 -->
        <!-- <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>
        
        <!-- 视图解析器 
            解析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>
    </beans>

        8.6.2 配置前端控制器

    参考入门程序。加载spring容器,配置springmvc前置控制器。

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>springmvc_mybatis1217</display-name>
      
      <!-- springmvc前端控制器 -->
      <servlet>
          <servlet-name>springmvc</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器,适配器等等)
              如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-servlet.xml(springmvc-servlet.xml)
           -->
          <init-param>
              <param-name>contextConfigLocation</param-name>
              <param-value>classpath: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>
    </web-app>

        8.6.3 编写Controller(就是Handler)

        8.6.4 编写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"%>
    <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>

      8.7 加载spring容器

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

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

    在web.xml中,添加spring容器监听器,加载spring容器。

    测试:http://localhost:8080/springmvc_mybatis/queryItem.action

  • 相关阅读:
    json 字符串解析mark
    Base64格式加载后台资源示例
    Visual SVN Server+TortoiseSVN进行源代码管理
    Android 高德地图 java.lang.UnsatisfiedlinkError Native method not found: com.autonavi.amap.mapcore.MapCore.nativeNewInstance:(Ljava/lang/String;)
    [Android] keytools生成jsk文件以及获取sha1码
    JavaScript:父页面与Iframe页面方法互调
    VMWare WorkStation中MacOS虛擬機無法啓動的問題
    Xamarin.Android调用百度地图
    C#中String与byte[]的相互转换
    Cordova总是弹出Connection to server was Unsuccessful
  • 原文地址:https://www.cnblogs.com/justdoitba/p/8335572.html
Copyright © 2020-2023  润新知