快速上手SSM(Spring,SpringMVC,Mybatis)框架整合项目

环境要求:

  • IDEA
  • MySQL 8.0.25
  • Tomcat 9
  • Maven 3.6

数据库环境:
创建一个存放书籍数据的数据库表

CREATE DATABASE `ssmbooks`;USE `ssmbooks`;DROP TABLE IF EXISTS `books`;CREATE TABLE `books` (`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',`bookName` VARCHAR(100) NOT NULL COMMENT '书名',`bookCounts` INT(11) NOT NULL COMMENT '数量',`detail` VARCHAR(200) NOT NULL COMMENT '描述',KEY `bookID` (`bookID`));INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES(1,'Java',1,'从入门到放弃'),(2,'MySQL',10,'从删库到跑路'),(3,'Linux',5,'从进门到进牢');

基本环境搭建:
1、新建一Maven项目!ssmbooks , 添加web的支持
2、导入相关的pom依赖!

                                junit            junit            4.12                                    mysql            mysql-connector-java            8.0.25                                    com.mchange            c3p0            0.9.5.2                                    javax.servlet            servlet-api            2.5                            javax.servlet.jsp            jsp-api            2.2                            javax.servlet            jstl            1.2                                    org.mybatis            mybatis            3.5.2                            org.mybatis            mybatis-spring            2.0.2                                    org.springframework            spring-webmvc            5.1.9.RELEASE                            org.springframework            spring-jdbc            5.1.9.RELEASE                            org.projectlombok            lombok            1.18.2            compile            

3、Maven资源过滤设置

                                        src/main/java                                    **/*.properties                    **/*.xml                                false                                        src/main/resources                                    **/*.properties                    **/*.xml                                false                        

4、建立基本结构和配置框架!

  • com.bai.pojo
  • com.bai.dao
  • com.bai.service
  • com.bai.controller
  • mybatis-config.xml
  • applicationContext.xml

Mybatis层编写

1、数据库配置文件 database.properties

jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/ssmbooks?useUnicode=true&characterEncoding=utf8jdbc.username=rootjdbc.password=root

2、IDEA关联数据库
3、编写MyBatis的核心配置文件

                                

4、编写数据库对应的实体类 com.bai.pojo.Books
使用lombok插件!

package com.bai.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data@AllArgsConstructor@NoArgsConstructorpublic class Books {    private int bookID;    private String bookName;    private int bookCounts;    private String detail;}

5、编写Dao层的 Mapper接口!

package com.bai.dao;import com.bai.pojo.Books;import org.apache.ibatis.annotations.Param;import java.util.List;public interface BookMapper {        //    添加一本书        int addBook(Books books);        //    删除一本书        int deleteBookById(@Param("bookId") int id);        //    更新一本书        int updateBook(Books books);        //    查询一本书        Books queryBookById(@Param("bookId") int id);        //    查询全部的书        List queryAllBook();        //    通过名字查询书籍        List queryBookByName(@Param("BookName") String BookName);}

6、编写接口对应的 Mapper.xml 文件。需要导入MyBatis的包;

            insert into ssmbooks.books ( bookName, bookCounts, detail)        values (#{bookName},#{bookCounts},#{detail})                delete from ssmbooks.books where bookID = #{bookId}                update ssmbooks.books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}        where bookID=#{bookID}                select * from ssmbooks.books where bookID=#{bookId}                select * from ssmbooks.books                select * from ssmbooks.books where bookName  like concat('%',#{BookName},'%')    

7、编写Service层的接口和实现类
接口:

package com.bai.service;import com.bai.pojo.Books;import java.util.List;public interface BookService {    //    添加一本书    int addBook(Books books);    //    删除一本书    int deleteBookById(int id);    //    更新一本书    int updateBook(Books books);    //    查询一本书通过id    Books queryBookById(int id);    //    查询全部的书    List queryAllBook();    //    查询一本书通过名字    List queryBookByName(String BookName);}

实现类:

package com.bai.service;import com.bai.dao.BookMapper;import com.bai.pojo.Books;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import java.util.List;@Service("BookServiceImpl")public class BookServiceImpl implements BookService{    //service层调dao层: 组合dao    @Autowired    private BookMapper bookMapper;    public void setBookMapper(BookMapper bookMapper) {        this.bookMapper = bookMapper;    }    public int addBook(Books books) {        return bookMapper.addBook(books);    }    public int deleteBookById(int id) {        return bookMapper.deleteBookById(id);    }    public int updateBook(Books books) {        return bookMapper.updateBook(books);    }    public Books queryBookById(int id) {        return bookMapper.queryBookById(id);    }    public List queryAllBook() {        return bookMapper.queryAllBook();    }    public List queryBookByName(String BookName) {        return bookMapper.queryBookByName(BookName);    }}

OK,到此,底层需求操作编写完毕!

Spring层

1、配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;
2、我们去编写Spring整合Mybatis的相关的配置文件;spring-dao.xml

                                                                                                                                                                                

3、Spring整合service层

    <!--    --><!--        --><!--    -->                

Spring层搞定!再次理解一下,Spring就是一个大杂烩,一个容器!对吧!

SpringMVC层

1、web.xml

                DispatcherServlet        org.springframework.web.servlet.DispatcherServlet                    contextConfigLocation                        classpath:applicationContext.xml                1                DispatcherServlet        /                    encodingFilter                    org.springframework.web.filter.CharacterEncodingFilter                            encoding            utf-8                        encodingFilter        /*                    15    

2、spring-mvc.xml

                                            

3、Spring配置整合文件,applicationContext.xml

            

Controller 和 视图层编写
**1、BookController 类编写 **

package com.bai.controller;import com.bai.pojo.Books;import com.bai.service.BookService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import java.util.List;@Controller@RequestMapping("/book")public class BookController {    //controller层调service层    @Autowired    @Qualifier("BookServiceImpl")    private BookService bookService;    //查询全部的书籍,并且返回到一个数据展示页面    @RequestMapping("/allbook")    public String list(Model model) {        List list = bookService.queryAllBook();        model.addAttribute("list", list);        return "allbook";    }//    跳转到添加书籍页面    @RequestMapping("/toAddBook")    public String toAddPaper() {        return "addBook";    }    //添加书籍的请求    @RequestMapping("/addBook")    public String addBook(Books books){        System.out.println("Books=>:"+books);        bookService.addBook(books);        return "redirect:/book/allbook";    }    //跳转到修改书籍页面    @RequestMapping("/toUpdate")    public String toUpdatePaper(int id,Model model){        Books books = bookService.queryBookById(id);        model.addAttribute("QBook", books);        return "updateBook";    }    //修改书籍请求    @RequestMapping("/updateBook")    public String UpdateBook(Books books,Model model) {        System.out.println("UpdateBook=>:"+books);        bookService.updateBook(books);//        出现的问题:我们提交了修改的SQL请求,但是修改失败。//        我们看一下sql语句,能否执行成功? 执行失败:发现sql语句需要传递一个id进行修改//        Books books1 = bookService.queryBookById(books.getBookID());//        model.addAttribute("books1", books1);        return "redirect:/book/allbook";    }    //删除书籍请求    @RequestMapping("/del/{bookid}")    public String DeleteBook(@PathVariable("bookid") int id) {        bookService.deleteBookById(id);        return "redirect:/book/allbook";    }    //通过名字查询书籍请求    @RequestMapping("/queryBook")    public String queryBook(String queryBookName,Model model) {        List list = bookService.queryBookByName(queryBookName);        model.addAttribute("list", list);        if (list.size()==0){            model.addAttribute("msg", "未查到数据");        }        return "allbook";    }}

2、编写首页 index.jsp

      首页        a {      text-decoration: none;      color: black;      font-size: 18px;    }    h3 {      width: 180px;      height: 38px;      margin: 100px auto;      text-align: center;      line-height: 38px;      background: deepskyblue;      border-radius: 4px;    }      

进入书籍页面

3、书籍列表页面 allbook.jsp

    书籍列表            

书籍列表 —— 显示所有书籍

新增书籍 显示全部书籍
${msg}
书籍编号 书籍名字 书籍数量 书籍详情 操作
${book.getBookID()} ${book.getBookName()} ${book.getBookCounts()} ${book.getDetail()} 更改 | 删除

5、添加书籍页面:addBook.jsp

    新增书籍            

新增书籍

书籍名称:


书籍数量:


书籍详情:


7、修改书籍页面 updateBook.jsp

    <修改信息            

修改信息

书籍名称: 书籍数量: 书籍详情:

配置Tomcat,进行运行!

项目结构


这里我们只是使用了SSM框架完成了基本的增删改查功能模块的网页