博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SSM-Spring-22:Spring+Mybatis+JavaWeb的整合
阅读量:6928 次
发布时间:2019-06-27

本文共 10889 字,大约阅读时间需要 36 分钟。

 

 

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

 

 

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

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

 

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

 

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

 

步骤开始:

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

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

 

Y2167DAWNALLDEMO
cn.dawn
1.0-SNAPSHOT
4.0.0
02Spring
war
02Spring Maven Webapp
http://maven.apache.org
junit
junit
4.12
test
org.springframework
spring-beans
4.2.0.RELEASE
org.springframework
spring-context
4.2.0.RELEASE
org.aspectj
aspectjweaver
1.8.7
org.springframework
spring-jdbc
4.2.0.RELEASE
mysql
mysql-connector-java
5.1.39
c3p0
c3p0
0.9.1.2
org.apache.commons
commons-dbcp2
2.1.1
com.alibaba
druid
1.1.6
org.mybatis
mybatis
3.2.2
org.mybatis
mybatis-spring
1.2.1
org.springframework
spring-web
4.2.0.RELEASE
javaee
javaee-api
5
jstl
jstl
1.2
src/main/java
**/*.xml

 

  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配置文件

 

INSERT INTO book(bookname,bookauthor,bookprice) VALUES (#{bookName},#{bookAuthor},#{bookPrice})

 

    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.Driverjdbc.url=jdbc:mysql:///s2228jdbc.username=rootjdbc.password=

 

      3.2mybatis-config.xml

 

 

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

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

      3.3ApplicationContext-day23ssm.xml(你们可以改这个名字的,一会调用的时候改掉就可以了,不要学死,灵活应变,举一反三)

 

 

  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" %>    添加成功    

添加${bookName}成功

 

      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" %>    添加图书页面    
书名:
作者:
价格:

 

    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

 

Archetype Created Web Application
contextConfigLocation
classpath:ApplicationContext-day23ssm.xml
org.springframework.web.context.ContextLoaderListener
BookServlet
cn.dawn.day23ssm.servlet.BookServlet
BookServlet
/BookServlet
index.jsp

 

 

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

  servlet处的

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

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

 

 

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

转载请注明出处:

转载于:https://www.cnblogs.com/DawnCHENXI/p/8597436.html

你可能感兴趣的文章
流程 - 发布【敏捷方法之Scrum v0.2.pdf】
查看>>
STM32学习笔记(12)-DMA初步
查看>>
Java Socket例程1
查看>>
使用TortoiseSVN管理个人文档和项目代码
查看>>
TP复习12
查看>>
『原创』手把手教你用c#做个Splash(启动屏幕)
查看>>
oracle 基本操作
查看>>
Java问题抽象和递归(母羊生母羊问题为例)
查看>>
Pro Android 4 第五章 理解Intent
查看>>
用python的minidom解析xml(转载)
查看>>
费马小定理在公钥加密中的应用及原理
查看>>
使用 TestLink 进行测试管理(转载)
查看>>
Python学习手记——Using the Python Interpreter
查看>>
[Linux 虚拟化] Linux 中使用 KVM
查看>>
How to slove the problem of Garbage Characters of Chinese and Errors of Images in Qt
查看>>
Google Analytics初步接触
查看>>
ASP.NET MVC与Sql Server建立连接
查看>>
Windows Live Messenger大量邀请发放
查看>>
publishing failed with multiple errors eclipse
查看>>
hibernate not support decode
查看>>