Spring + SpringMVC + Mybatis整合流程

1      需求

  1.1     客户列表查询

  1.2     根据客户姓名模糊查询

2      整合思路

第一步:整合dao层

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

第二步:整合service层

通过spring管理service层,service调用mapper接口。使用配置方式将service接口配置在spring配置文件中,并且进行事务控制。

第三步:整合springMVC

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

3      准备环境

3.1     数据库版本
    mysql5.7

3.2    
编译器
    eclipse

3.3    
Jar 包

3.3.1    
spring的jar包

3.3.2    
spring与mybatis的整合jar包

3.3.3    
mybatis的jar包

3.3.4    
数据库驱动包

3.3.5    
log4j包

3.3.6    
log4j配置文件

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:\mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout

3.3.7     dbcp数据库连接池包

3.3.8     jstl包

4      整合dao

4.1      sqlMapconfig.xml

mybatis的配置文件:

<?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="com.haohan.ssm.po" />
</typeAliases>
<!-- 配置mapper映射文件 -->
<mappers>
<!-- 加载 原始dao使用映射文件 -->
<!-- <mapper resource="sqlmap/User.xml" /> --
<!--批量mapper扫描 遵循规则:将mapper.xml和mapper.java文件放在一个目录 且文件名相同 ,现在由spring配置扫描-->
<!-- <package name="cn.itcast.ssm.dao.mapper" /> -->
</mappers>
</configuration>

4.2      db.properties数据库配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/haohan1?characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123456

4.3     applicationContext-dao.xml

spring在这个xml文件中配置dbcp连接池,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: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">
<!--1. 数据源 -->
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置dbcp连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.name}"></property>
<property name="password" value="${jdbc.password}"</property>
</bean>
<!--2. sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 3. mapper的批量扫描-->
<!-- mapper的批量扫描 :从mapper包中扫描mapper接口,自动创建代理对象并且在spring容器中注册。
遵循的规范:需要将mapper的接口类名和mapper.xml映射文件名保持一致,且在一个目录中。
自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包名
如果扫描多个包,用半角逗号分开
-->
<property name="basePackage" value="cn.haohan.ssm.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>

4.4     逆向工程生成po类和mapper接口和mapper.xml文件

参考:http://how2j.cn/k/mybatis/mybatis-generator/1376.html

生成如下图的文件:

4.5     自定义mapper接口和xml文件,以及po的包装类

4.5.1     CustomMapper.java

public interface CustomMapper {
public List<HhCustom> findAllCustom(HhCustomVo hhCustomVo)throws Exception;
}

4.5.1     CustomMapper.xml

<?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">
<!-- namespace:命名空间,作用是对sql进行分类化管理,sql隔离 -->
<mapper namespace="cn.haohan.ssm.mapper.CustomMapper">
<sql id="query_custom_where">
<if test="hhCustom!=null">
<if test="hhCustom.name!=null and hhCustom.name!=''">
name like '%${hhCustom.name}%'
</if>
</if>
</sql>
<resultMap type="hhCustom" id="hhCustomResultMap">
<id column="id" property="id"/>
<result column="phone_number" property="phoneNumber"/>
</resultMap>
<select id="findAllCustom" parameterType="cn.haohan.ssm.po.HhCustomVo" resultMap="hhCustomResultMap">
SELECT
* FROM hh_custom
<where>
<include refid="query_custom_where"></include>
</where>
</select>
</mapper>

4.5.2     HhCustomVo

//客户的包装类
public class HhCustomVo {
//客户信息
private HhCustom hhCustom;
public HhCustom getHhCustom() {
return hhCustom;
}
public void setHhCustom(HhCustom hhCustom) { this.hhCustom = hhCustom;
}
}

4.6     数据库表结构

5      整合service

5.1     定义service接口

public interface CustomService {
public HhCustom findCustomById(Integer id)throws Exception;
public List<HhCustom> findAllCustom(HhCustomVo hhCustomVo)throws Exception;
}

5.2     service接口实现

public class CustomServiceImpl implements CustomService{

   @Autowired
HhCustomMapper hhCustomMapper;
@Autowired
CustomMapper customMapper;
@Override
public HhCustom findCustomById(Integer id) throws Exception {
// TODO Auto-generated method stub
return hhCustomMapper.selectByPrimaryKey(id);
}
@Override
public List<HhCustom> findAllCustom(HhCustomVo hhCustomVo) throws Exception {
// TODO Auto-generated method stub
return customMapper.findAllCustom(hhCustomVo);
}
}

5.3     在spring容器配置service(applicationContext-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: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">
<bean id="CustomServiceImpl" class="cn.haohan.ssm.service.impl.CustomServiceImpl"></bean>
</beans>

5.4   事务控制(applicationContext-transaction)

<?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">
<!-- 配置事务管理器
对mybatis操作数据库事务控制,spring使用jdbc事务控制类-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务增强(通知) -->
<tx:advice id="txadvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 设置进行事务操作的方法匹配规则 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS"/>
<tx:method name="get*" propagation="SUPPORTS"/>
<tx:method name="select*" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!-- aop操作 -->
<aop:config>
<aop:advisor advice-ref="txadvice" pointcut="execution(* cn.haohan.ssm.serivce.impl.*.*(..))"/>
</aop:config>
</beans>

6      整合springMVC

6.1      springmvc.xml

在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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 扫描加载handler -->
<context:component-scan base-package="cn.haohan.ssm.controller"></context:component-scan>
<!-- 注解映射器 -->
<!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
注解适配器
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> -->
<!-- 使用mvc:annotation-driven可代替上面的注解映射器和注解适配器mvc:annotation-driven默认加载许多参数绑定,比如json转换解析器,实际开发用mvc:annotation-driven-->
<mvc:annotation-driven>
</mvc:annotation-driven> <!-- 视图解析器
解析jsp,默认使用jstl标签,-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

6.2     配置前端控制器(web.xml)

<!-- 配置springmvc前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- contextConfigLocation:加载springmvc的配置文件(配置处理器适配器、映射器、视图解析器
默认加载的是/WEB-INF/servlet名称-servlet.xml( springmvc-servlet.xml)
-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<!--第一种:*.action ,访问以.action结尾的,由DispatcherServlet解析。
第二种:/ ,所有访问的地址都由DispatcherServlet解析,对于静态文件需要配置不让DispatcherServlet解析。
可以实现Restful风格。
-->
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>

6.3     编写controller

@Controller
public class CustomController { @Autowired
CustomService customService; //模糊查询客户
@RequestMapping("/findAllCustom")
public ModelAndView findAllCustom(HhCustomVo hhCustomVo) throws Exception {
List<HhCustom> customlist = customService.findAllCustom(hhCustomVo);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("customlist", customlist);
modelAndView.setViewName("customlist");
return modelAndView;
} //根据客户id查询
public ModelAndView findCustomByid(Integer id) throws Exception {
HhCustom hhCustom = customService.findCustomById(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("hhCustom", hhCustom);
modelAndView.setViewName("customlist");
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 name="customForm"
action="${pageContext.request.contextPath}/findAllCustom.action"
method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td>客戶名称:<input name="hhCustom.name" />
</td>
<%-- <td>客戶类型: <select name="customType">
<c:forEach items="${customType}" var="customType">
<option value="${customType.key }">${customType.value}</option>
</c:forEach>
</select>
</td> --%>
<td><button type="submit" value="查询" >查询</button></td>
</tr>
</table>
客戶列表:
<table width="100%" border=1>
<tr>
<th>选择</th>
<th>客戶名称</th>
<th>客戶邮箱</th>
<th>客戶电话</th>
<th>客户类型</th>
<!-- <th>操作</th> -->
</tr>
<c:forEach items="${customlist}" var="custom">
<tr>
<td><input type="checkbox" name="custom_id" value="${custom.id}" /></td>
<td>${custom.name }</td>
<td>${custom.mail }</td>
<td>${custom.phoneNumber }</td>
<td>${custom.category }</td>
<%--<td><fmt:formatDate value="${custom.birthday }" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<td><a href="${pageContext.request.contextPath }/items/editItems.action?id=${item.id }">修改</a></td> --%>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>

7      加载spring容器(web.xml)

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

8      Post方法中文乱码(web.xml)

<!-- post中文乱码 -->
<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>

9      结果

9.1     客户查询列表

9.2     根据模糊

ssm框架搭建和整合流程的更多相关文章

  1. ssm框架搭建整合测试

    下载各种jar包 mybatis下载 https://github.com/mybatis/mybatis-3/releases mysql驱动下载 http://mvnrepository.com/ ...

  2. SSM框架搭建教程(从零开始,图文结合)

    1.准备 IntelliJ IDEA Tomcat JDK Maven mysql spring.springmvc.mybatis 了解 现在假设如上条件你都具备,那么通过我这篇博客 你一定可以整合 ...

  3. SSM 框架-05-详细整合教程(Eclipse版)(Spring+SpringMVC+MyBatis)

    SSM 框架-05-详细整合教程(Eclipse版)(Spring+SpringMVC+MyBatis) 如果你使用的是 Intellij IDEA,请查看: SSM的配置流程详细的写了出来,方便很少 ...

  4. SSM框架搭建web服务器实现登录功能(Spring+SpringMVC+Mybatis)

    初学java EE,虽然知道使用框架会使开发更加便捷高效,但是对于初学者来说,感到使用框架比较迷惑,尤其是各种jar包的引用.各种框架的配置.注解的使用等等. 最好的学习方法就是实践,于是下载了一个现 ...

  5. SSM 框架搭建

    SSM框架搭建(Spring.SpringMVC.Mybatis) 一:基本概念 Spring :      Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框 ...

  6. 实习小结(二)--- SSM框架搭建

    SSM项目框架搭建 前几天做了一个学生信息管理的项目,使用纯控制台输入,查询数据库,将信息在控制台中打印,功能完善得差不多之后,老师让将这个项目移植到Web中,使用Spring+SpringMVC+M ...

  7. SSM 框架-06-详细整合教程(IDEA版)(Spring+SpringMVC+MyBatis)

    SSM 框架-06-详细整合教程(IDEA版)(Spring+SpringMVC+MyBatis) SSM(Spring.Spring MVC和Mybatis)如果你使用的是 Eclipse,请查看: ...

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

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

  9. 01-电子商城项目介绍及ssm框架搭建

    1.B2C电商项目功能及架构 1.1功能列表 1.2系统架构(soa架构) 2.后台管理系统工程搭建及测试 ypMall,ypMall-manager-web ypMall为父项目,管理子项目的jar ...

随机推荐

  1. Java数组的复制全解

    1.将一个基本数据类型数组的引用赋值给另一个数组 public class Array_copy { int[] array1=new int[]{1,2,3,4,5,6}; int[] array2 ...

  2. 使用MongoDB存储集合的一些问题

    这两天在工作中被Mongo集合存储给整得头大,当然也是我的认知太浅,所以下面我来分享下我所遇到的这个问题希望有大佬能给出更好的解决方案, 1.需求: 存储一个从前端接收未知数据类型的集合 例: 由于是 ...

  3. HTML学习笔记8:表单

      什么是表单?     一个网页表单可以将用户输入的数据发送到服务器进行处理.因为互联网用户使用复选框,单选按钮或文本字段填写表格,所以WebForms的形式类似文件或数据库.例如,WebForms ...

  4. Page_Load不要忘了if (!IsPostBack)

    Page_Load不要忘了if (!IsPostBack) 问题:在DropDownList的SelectedIndexChanged事件中绑定数据,运行时,DropDownList控件的Select ...

  5. JavaScript 之函数

    刚开 始学习 JS 时,挺不习惯它函数的用法,就比如一个 function 里面会嵌套一个 function,对于函数里创建变量的作用域也感到很迷惑,这个的语法和 JAVA 相差太多,为此,阅读了&l ...

  6. 在AspNetCore 中 使用Redis实现分布式缓存

    AspNetCore 使用Redis实现分布式缓存 上一篇讲到了,Core的内置缓存:IMemoryCache,以及缓存的基础概念.本篇会进行一些概念上的补充. 本篇我们记录的内容是怎么在Core中使 ...

  7. java序列化反序列化深入探究(转)

    When---什么时候需要序列化和反序列化: 简单的写一个hello world程序,用不到序列化和反序列化.写一个排序算法也用不到序列化和反序列化.但是当你想要将一个对象进行持久化写入文件,或者你想 ...

  8. 一个比ack速度快n倍的代码搜索工具: ag

    一个比ack速度快n倍的代码搜索工具:  ag 银搜索者(The Silver Searcher) 一个类似于代码搜索工具ack,着重于速度. Github:   https://github.com ...

  9. ARP攻击之Kali Linux局域网断网攻击

    特别声明: 我们学习研究网络安全技术的目的应是为了维护网络世界的安全,保护自己和他人的私有信息不被非法窃取和传播.请您遵守您所在地的法律,请勿利用本文所介绍的相关技术做背离道德或者违反法律的事情. S ...

  10. 使用XAMPP和DVWA在Windows7上搭建渗透测试环境

    前言: XAMPP是一个Web应用程序运行环境集成软件包,包括MySQL.PHP.PerI和Apache的环境及Apache.MySQL.FilleZilla.Mercury和Tomecat等组件.D ...