【Spring+SpringMVC+MyBatis深入学习及搭建】14.SpringMVC和MyBatis整合

转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7010363.html 

前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十三)——SpringMVC入门程序(二)

1.需求

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

2.整合思路

springmvc+mybatis的系统架构:

【Spring+SpringMVC+MyBatis深入学习及搭建】14.SpringMVC和MyBatis整合_第1张图片

第一步:整合dao层

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

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

第二步:整合service层

  通过spring管理service接口。

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

  实现事务控制。

第三步:整合springMvc

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

3.环境准备

数据库环境:mysql5.6

【Spring+SpringMVC+MyBatis深入学习及搭建】14.SpringMVC和MyBatis整合_第2张图片

java环境:

jdk1.7

MyEclipse2014

springmvc版本:spring3.2

所需要的jar包:

数据库驱动包

mybatis的jar包

mybatis的spring的整合包

log4j包

dbcp数据库连接池包

spring3.2所有jar包

jstl包

过程结构目录:

【Spring+SpringMVC+MyBatis深入学习及搭建】14.SpringMVC和MyBatis整合_第3张图片【Spring+SpringMVC+MyBatis深入学习及搭建】14.SpringMVC和MyBatis整合_第4张图片

4.整合dao

 mybatis和spring进行整合。

4.1 db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisdemo
jdbc.username=root
jdbc.password=

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

4.3 sqlMapConfig.xml

在classpath下创建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>
     

    
    <typeAliases>
        
        <package name="joanna.yan.ssm.po"/>
    typeAliases>

    
    
    
 configuration>
复制代码

4.4 applicationContext-dao.xml

在classpath下创建spring/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 ">
    
    
    <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>
    
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
        
        <property name="dataSource" ref="dataSource" />
    bean>
    
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="basePackage" value="joanna.yan.ssm.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    bean>
    
beans>
复制代码

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

详情见:Spring+SpringMVC+MyBatis深入学习及搭建(十)——MyBatis逆向工程

【Spring+SpringMVC+MyBatis深入学习及搭建】14.SpringMVC和MyBatis整合_第5张图片

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

4.6手动定义商品查询mapper

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

4.6.1 ItemsMapperCustom.xml

sql语句:

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

复制代码
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="joanna.yan.ssm.mapper.ItemsMapperCustom" >
    
    <sql id="query_items_where">
        
        
        <if test="itemsCustom!=null">
            <if test="itemsCustom.name!=null and itemsCustom.name!=''">
                items.name LIKE '%${itemsCustom.name}%'
            if>
        if>
    sql>
    
    
    
    <select id="findItemsList" parameterType="joanna.yan.ssm.po.ItemsQueryVo" 
    resultType="joanna.yan.ssm.po.ItemsCustom">
        SELECT items.* FROM items
        <where>
            <include refid="query_items_where">include>
        where>
    select>
mapper>
复制代码

4.6.2 ItemsMapperCustom.java

public interface ItemsMapperCustom {
    //商品查询列表
    public List findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
}

5.整合service

让spring管理service接口。

5.1定义service接口

复制代码
package joanna.yan.ssm.service;

import java.util.List;
import joanna.yan.ssm.po.ItemsCustom;
import joanna.yan.ssm.po.ItemsQueryVo;

public interface ItemsService {
    //商品查询列表
    public List findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
}
复制代码
复制代码
package joanna.yan.ssm.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import joanna.yan.ssm.mapper.ItemsMapperCustom;
import joanna.yan.ssm.po.ItemsCustom;
import joanna.yan.ssm.po.ItemsQueryVo;
import joanna.yan.ssm.service.ItemsService;

public class ItemsServiceImpl implements ItemsService{
    
    @Autowired
    private ItemsMapperCustom itemsMapperCustom;

    @Override
    public List findItemsList(ItemsQueryVo itemsQueryVo)
            throws Exception {
        //通过ItemsMapperCustom查询数据库
        return itemsMapperCustom.findItemsList(itemsQueryVo);
    }
}
复制代码

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

 在classpath下创建spring/applicationContext-service.xml,文件中配置service。

复制代码
<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="itemsService" class="joanna.yan.ssm.service.impl.ItemsServiceImpl"/>
    
beans>
复制代码

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

在classpath下创建spring/applicationContext-service.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="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="insert*" 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:config>
        
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* joanna.yan.ssm.service.impl.*.*(..))"/>
    aop:config>
beans>
复制代码

6.整合springmvc 

6.1 springmvc.xml

在classpath下创建spring/springvc.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 ">
        
    
    <context:component-scan base-package="joanna.yan.ssm.controller">context:component-scan>
    
    
    
    
    
    
    <mvc:annotation-driven>mvc:annotation-driven>
    
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>
beans>
复制代码

6.2配置前端控制器

参考入门程序:Spring+SpringMVC+MyBatis深入学习及搭建(十二)——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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringMVC_MyBatisdisplay-name>
  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>

  
  <servlet>
      <servlet-name>springmvcservlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
      
      <init-param>
          <param-name>contextConfigLocationparam-name>
          <param-value>classpath:spring/springmvc.xmlparam-value>
      init-param>
      
      <load-on-startup>1load-on-startup>
  servlet>
  
  <servlet-mapping>
      <servlet-name>springmvcservlet-name>
      
      <url-pattern>*.actionurl-pattern>
  servlet-mapping>
  
web-app>
复制代码

6.3编写Controller(就是Handler)

复制代码
@Controller
public class ItemsController {
    
    @Autowired
    private ItemsService itemsService;

    //商品查询http://localhost:8080/SpringMVC_MyBatis/queryItems.action
    @RequestMapping("/queryItems")
    public ModelAndView queryItems() throws Exception{
        //调用service查找数据库,查询商品列表
        List itemsList=itemsService.findItemsList(null);
        
        //返回ModelAndView
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("itemsList", itemsList);
        //指定视图
//        modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
        //下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为
        modelAndView.setViewName("items/itemsList");
        return modelAndView;
    }
}
复制代码

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"%>
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>
复制代码

7.加载spring容器

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

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

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

复制代码
  
  <context-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>/WEB-INF/classes/spring/applicationContext-*.xmlparam-value>
  context-param>
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
复制代码

8.商品查询调试

访问地址:http://localhost:8080/SpringMVC_MyBatis/queryItems.action

查询结果:

【Spring+SpringMVC+MyBatis深入学习及搭建】14.SpringMVC和MyBatis整合_第6张图片

注意:在进行项目发布时,报错

复制代码
javax.servlet.ServletException: Servlet.init() for servlet springmvc threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)
复制代码

原因:服务器上Tomcat的jdk版本过高是1.8,而Spring的jar是3.2。

解决:降低jdk版本至1.7或将Spring的jar升至4.0及以上。

如果此文对您有帮助,微信打赏我一下吧~ 

【Spring+SpringMVC+MyBatis深入学习及搭建】14.SpringMVC和MyBatis整合_第7张图片

 

作者:Joanna.Yan
出处:http://www.cnblogs.com/Joanna-Yan/
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。

  

你可能感兴趣的:(#,SpringMVC,#,SSM,#,MyBatis,SSM,java,spring,mvc,myBatis)