------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------

众所周知,框架Spring来整合别的框架,但是Mybatis出现的晚,Spring就没有给他提供支持,那怎么办呢?Mybatis说,我吃点亏,我给你提供整合的jar,所以那个整合的jar包就叫mabatis-spring。jar

由于SpringMVC和Spring天然集成,所以,Spring整合了Mabatis就证明你ssm整合就搞定了

整合并不只是jar包的堆砌,而是一个框架的部分功能要交给另外一个框架进行完成,调度

写个案例,购买添加图书的Spring+Mabatis+JavaWeb的案例

步骤开始:

  1.引入jar包,修改build节点:

    我之前案例的节点,可能这个案例用不到,但是也一块扔上来了

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>Y2167DAWNALLDEMO</artifactId>
<groupId>cn.dawn</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.</modelVersion>
<artifactId>02Spring</artifactId>
<packaging>war</packaging>
<name>02Spring Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!--单元测试的依赖 ctrl+shif+/-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency> <!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2..RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2..RELEASE</version>
</dependency> <!--aop使用的jar-->
<dependency>
<groupId> org.aspectj</groupId >
<artifactId> aspectjweaver</artifactId >
<version> 1.8.</version>
</dependency> <!--spring jdbc-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2..RELEASE</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.</version>
</dependency> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.</version>
</dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.</version>
</dependency> <!--mybatis jar包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.</version>
</dependency> <!--Mybatis+Spring整合-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.</version>
</dependency> <!-- Spring整合JavaWeb的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2..RELEASE</version>
</dependency> <!--javaee jar-->
<dependency>
<groupId>javaee</groupId>
<artifactId>javaee-api</artifactId>
<version></version>
</dependency> <!--jstl表达式-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency> </dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>

  2.准备数据库:

  3.分层开发开始:

    3.1entity层

      Book实体类

package cn.dawn.day23ssm.entity;

public class Book {
private Integer bookID;
private String bookName;
private String bookAuthor;
private Integer bookPrice; public Book() {
} public Book(String bookName, String bookAuthor, Integer bookPrice) {
this.bookName = bookName;
this.bookAuthor = bookAuthor;
this.bookPrice = bookPrice;
} public Integer getBookID() {
return this.bookID;
} public void setBookID(Integer bookID) {
this.bookID = bookID;
} public String getBookName() {
return this.bookName;
} public void setBookName(String bookName) {
this.bookName = bookName;
} public String getBookAuthor() {
return this.bookAuthor;
} public void setBookAuthor(String bookAuthor) {
this.bookAuthor = bookAuthor;
} public Integer getBookPrice() {
return this.bookPrice;
} public void setBookPrice(Integer bookPrice) {
this.bookPrice = bookPrice;
}
}

    3.2dao层

      接口IBookDAO

package cn.dawn.day23ssm.dao;

import cn.dawn.day23ssm.entity.Book;

/**
* Created by Dawn on 2018/3/17.
*/
public interface IBookDAO {
//添加
public int insertBook(Book book) throws Exception;
}

      同名的IBookDAO.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">
<mapper namespace="cn.dawn.day23ssm.dao.IBookDAO"> <insert id="insertBook">
INSERT INTO book(bookname,bookauthor,bookprice) VALUES (#{bookName},#{bookAuthor},#{bookPrice})
</insert> </mapper>

    3.3service层

      IBookService接口:

package cn.dawn.day23ssm.service;

import cn.dawn.day23ssm.entity.Book;

/**
* Created by Dawn on 2018/3/17.
*/
public interface IBookService {
//添加
public int insertBook(Book book) throws Exception;
}

      BookServiceImpl刚才那个接口的实现类

package cn.dawn.day23ssm.service;

import cn.dawn.day23ssm.dao.IBookDAO;
import cn.dawn.day23ssm.entity.Book;
import org.springframework.transaction.annotation.Transactional; /**
* Created by Dawn on 2018/3/17.
*/
public class BookServiceImpl implements IBookService {
private IBookDAO dao; //开启事务
@Transactional
public int insertBook(Book book) throws Exception {
return dao.insertBook(book);
} public IBookDAO getDao() {
return dao;
} public void setDao(IBookDAO dao) {
this.dao = dao;
}
}

      此处我做了事务的开启

  3.我的习惯是在此处开始写配置文件,走个单测再去和javaweb打交道

    所以此处的步骤就是三个大配置文件

      3.1jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///s2228
jdbc.username=root
jdbc.password=

      3.2mybatis-config.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="cn.dawn.day23ssm.entity"></package>
</typeAliases>
</configuration>

      此处的mybatis只做了别名,但是这个案例中没有用,只是提一下,如果做查询的时候,别名从这儿设置,我一会也给把加入spring的地方也标出来

      它的mappers,properties都不从这儿设置,这就印证了我之前的一句话,整合并不只是jar包的堆砌,而是一个框架的部分功能要交给另外一个框架进行完成,调度

      3.3ApplicationContext-day23ssm.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:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--配置jdbc。properties-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <!--阿里的Druid-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> <!--dao层-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--这儿的mybatis配置文件中只做别名,其他的都由spring整合了-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!--映射扫描器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.dawn.day23ssm.dao"></property>
</bean>
<!--service-->
<bean id="bookService" class="cn.dawn.day23ssm.service.BookServiceImpl">
<property name="dao" ref="IBookDAO"></property>
</bean>
<!--事务管理器-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--事务开启,注解版-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"></tx:annotation-driven> </beans>

  4.jsp页面和servlet

    4.1jsp页面

      success.jsp

<%--
Created by IntelliJ IDEA.
User: Dawn
Date: //
Time: :
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>添加成功</title>
</head>
<body>
<h2 style="text-align: center;color: red">添加${bookName}成功</h2>
</body>
</html>

      addBook.jsp

<%--
Created by IntelliJ IDEA.
User: Dawn
Date: //
Time: :
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>添加图书页面</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/BookServlet">
书名:<input type="text" name="bookName">
作者:<input type="text" name="bookAuthor">
价格:<input type="text" name="bookPrice">
<input type="submit" value="添加图书">
</form>
</body>
</html>

    4.2servlet层

      BookServlet

package cn.dawn.day23ssm.servlet;

import cn.dawn.day23ssm.entity.Book;
import cn.dawn.day23ssm.service.IBookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* Created by Dawn on 2018/3/17.
*/
public class BookServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决乱码
request.setCharacterEncoding("utf-8");
//获取书名
String bookName = request.getParameter("bookName");
//获取作者
String bookAuthor = request.getParameter("bookAuthor");
//获取价格
String bookPriceStr = request.getParameter("bookPrice");
Integer bookPrice=Integer.parseInt(bookPriceStr);
//创建图书对象
Book book=new Book(bookName,bookAuthor,bookPrice);
//创建service对象
     //采用优雅的方式:
     //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ApplicationContext applicationContext= WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
      
//ApplicationContext applicationContext=new ClassPathXmlApplicationContext("ApplicationContext-day23ssm.xml");
IBookService bookService = (IBookService)applicationContext.getBean("bookService");
//调用方法
try {
int result = bookService.insertBook(book);
//根据返回结果判断是否成功
if (result>){
//把结果传过去
request.setAttribute("bookName",bookName);
//成功,转发到Index页面
request.getRequestDispatcher("/success.jsp").forward(request,response); }else {
//失败,重定向到刚才的页面
response.sendRedirect("/ssm/addBook.jsp");
} } catch (Exception e) {
e.printStackTrace();
} } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}

    这儿有我之前埋的一个坑,我这儿用的javaee是5的版本,不是6.0,没法用注解版,所以还得到web.xml中配置一道

    4.3web。xml

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app>
<display-name>Archetype Created Web Application</display-name> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext-day23ssm.xml</param-value>
</context-param>
<!--监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>BookServlet</servlet-name>
<servlet-class>cn.dawn.day23ssm.servlet.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookServlet</servlet-name>
<url-pattern>/BookServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

  这儿有一处之前没有见到过

  servlet处的

  ApplicationContext applicationContext= WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());

 和web.xml中的监听器和配置
 这是什么呢?
  这是一个优雅的方式,
 总所周知,你将之前单测的那种方式你直接拖过来用,那在servlet中会造成什么后果呢?
  就是每一次访问servlet你就对spring容器进行一次初始化工作,这里面的bean因为是单例的,所以都会生成一次,相当耗损性能
 那么怎么办?
  你想servletcontext就是在web容器中从一开始到结束过程中都可以访问到的,那么我们在web容器一启动的时候就将spring容器放到servletcontext中岂不美哉,之后就不用new了
  

-------笔者:晨曦Dawn-------

转载请注明出处:http://www.cnblogs.com/DawnCHENXI/p/8597436.html

SSM-Spring-22:Spring+Mybatis+JavaWeb的整合的更多相关文章

  1. SSM 三大框架系列:Spring 5 + Spring MVC 5 + MyBatis 3.5 整合(附源码)

    之前整理了一下新版本的 SSM 三大框架,这篇文章是关于它的整合过程和项目源码,版本号分别为:Spring 5.2.2.RELEASE.SpringMVC 5.2.2.RELEASE.MyBatis ...

  2. JAVA 框架 / SSM / SSM SPRING+SPING MVC + MYBATIS 三大框架整合详细步骤

    http://how2j.cn/k/ssm/ssm-tutorial/1137.html

  3. Spring boot 、mybatis 和 swagger 整合

    文件路径 添加依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="h ...

  4. Spring Boot 与 Mybatis、Mysql整合使用的例子

    第一步: 创建一个SpringBoot的工程,在其中的Maven依赖配置中添加对JDBC.MyBatis.Mysql Driver的依赖具体如下: <!-- JDBC --> <de ...

  5. SSM 即所谓的 Spring MVC + Spring + MyBatis 整合开发。

    SSM 即所谓的 Spring MVC + Spring + MyBatis 整合开发.是目前企业开发比较流行的架构.代替了之前的SSH(Struts + Spring + Hibernate) 计划 ...

  6. SSM(spring mvc+spring+mybatis)学习路径——2-2、spring MVC拦截器

    目录 2-2 Spring MVC拦截器 第一章 概述 第二章 Spring mvc拦截器的实现 2-1 拦截器的工作原理 2-2 拦截器的实现 2-3 拦截器的方法介绍 2-4 多个拦截器应用 2- ...

  7. 一步步教你整合SSM框架(Spring MVC+Spring+MyBatis)详细教程重要

    前言 SSM(Spring+SpringMVC+Mybatis)是目前较为主流的企业级架构方案,不知道大家有没有留意,在我们看招聘信息的时候,经常会看到这一点,需要具备SSH框架的技能:而且在大部分教 ...

  8. SSM(Spring MVC +Spring+Mybatis)整合——maven工程

    所谓的SSM 其实就是Spring MVC下整合mybatis. 具体的定义网络上都有,很详细. 这里只说项目的搭建步骤. 第一步 新建maven工程 工程目录如下: 配置pom.xml文件,引入所需 ...

  9. [置顶] Java Web学习总结(24)——SSM(Spring+SpringMVC+MyBatis)框架快速整合入门教程

    1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One  ...

随机推荐

  1. Android 添加library的时候出错添加不上

    在向android工程中导入library的时候,会和出现导入不成功,打开查看添加library界面,会发现你添加的library的路径出现D:/work/...?类似的情况,但是别的工程使用的时候又 ...

  2. ITU-T Technical Paper: IP网络测量模型

    本文翻译自ITU-T的Technical Paper:<How to increase QoS/QoE of IP-based platform(s) to regionally agreed ...

  3. x265 (HEVC编码器,基于x264) 介绍

    x265要出来了.简单翻译了一下项目网站首页的介绍. x265是一个开源项目,是一个将视频编码为h.265/高效率的视频编码(HEVC)格式的免费的库,在GNU GPL条款下发布.它的源代码是免费提供 ...

  4. 推荐一些用CRF做图像语义分割的资源

    原文地址:http://blog.sina.com.cn/s/blog_5309cefc01014nri.html 首先是code,以前找了很多,但发现比较好用的有: 1. Matlab版的UGM:h ...

  5. LeetCode之“散列表”:Valid Sudoku

    题目链接 题目要求: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku boar ...

  6. 循环赛日程编排c代码

    #include <stdio.h> int m,s,n; int i,j; int a[100][100]; int sf(int n) { if(n%2!=0) printf(&quo ...

  7. HP-Socket快速入门:分包、粘包解析

    环境配置 vs2015 windows7 64位 hp-socket 5.0 安装hp-socket 新建控制台项目TelnetServer,打开Nuget管理工具,搜索hp-socket: 安装成功 ...

  8. Python进程与线程

    进程与线程:*进程: 进程是系统中程序执行和资源分配的基本单元, 每个进程都有自己的数据段(存储数据).代码段(存储代码).堆栈段(对象和变量). # 全局变量等资源在多个进程中不能          ...

  9. postgresql to_char 问题

    select create_time from  xxx; select to_char(create_time,'yyyy-MM-dd HH24:mm:ss') as  create_time fr ...

  10. php插入mysql中文数据出现乱码

    $con = mysqli_connect(DB_HOST, DB_USER, DB_PWD, $dbname) or die('数据库连接失败'); mysqli_set_charset($con, ...