SSM-Spring-22:Spring+Mybatis+JavaWeb的整合

 

 

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

 

 

众所周知,框架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.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.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>

        <!--aop使用的jar-->
        <dependency>
            <groupId> org.aspectj</groupId >
            <artifactId> aspectjweaver</artifactId >
            <version> 1.8.7</version>
        </dependency>


        <!--spring jdbc-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</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.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>



        <!--mybatis jar包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.2</version>
        </dependency>

        <!--Mybatis+Spring整合-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.1</version>
        </dependency>

        <!-- Spring整合JavaWeb的包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>

        <!--javaee  jar-->
        <dependency>
            <groupId>javaee</groupId>
            <artifactId>javaee-api</artifactId>
            <version>5</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: 2018/3/17
  Time: 14:39
  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: 2018/3/17
  Time: 14:41
  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>0){ //把结果传过去 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

posted @ 2018-03-18 20:56  晨曦Dawn  阅读(569)  评论(0编辑  收藏  举报