人生中第一个ssm框架整合

ssm框架整合

标签:增删改查、分页、测试、事务、restful风格

ssm框架结构图

人生中第一个ssm框架整合_第1张图片

1.数据库建表

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`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');

2.pom文件中加入依赖

<dependencies>
    <!-- SpringMVC -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
    </dependency>

    <!-- Spring 持久化层所需依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
    </dependency>

    <!-- 日志 -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
    </dependency>

    <!-- ServletAPI -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <scope>provided</scope>
    </dependency>

    <!-- Spring5Thymeleaf整合包 -->
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring5</artifactId>
    </dependency>

    <!-- Mybatis核心 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
    </dependency>

    <!-- MySQL驱动 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <!-- 数据源 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
    </dependency>

    <!-- junit5 -->
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- Spring 的测试功能 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
    </dependency>

    <!-- MybatisSpring 的整合包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
    </dependency>

    <!-- Mybatis分页插件 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
    </dependency>
  </dependencies>

3.pojo层创建实体类

//创建实体类,实体类属性与表字段对应
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;

    public Books() {
    }

    public Books(int bookID, String bookName, int bookCounts, String detail) {
        this.bookID = bookID;
        this.bookName = bookName;
        this.bookCounts = bookCounts;
        this.detail = detail;
    }

    public int getBookID() {
        return bookID;
    }

    public void setBookID(int bookID) {
        this.bookID = bookID;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public int getBookCounts() {
        return bookCounts;
    }

    public void setBookCounts(int bookCounts) {
        this.bookCounts = bookCounts;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    @Override
    public String toString() {
        return "Books{" +
                "bookID=" + bookID +
                ", bookName='" + bookName + '\'' +
                ", bookCounts=" + bookCounts +
                ", detail='" + detail + '\'' +
                '}';
    }
}

4.加入jdbc的配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///java0625?useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.pwd=root

5.加入日志配置文件


<configuration debug="true">
    
    <appender name="STDOUT"
              class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            
            
            <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%npattern>
        encoder>
    appender>

    
    
    <root level="WARN">
        
        <appender-ref ref="STDOUT" />
    root>
configuration>

6.加入spring-mybatis配置文件


<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: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
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    <context:component-scan base-package="com.atguigu.service"/>
    
    

    
    <context:property-placeholder location="classpath:jdbc.properties"/>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.pwd}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        
        <property name="dataSource" ref="dataSource"/>

        
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <props>
                            
                            <prop key="reasonable">trueprop>
                            
                            <prop key="helperDialect">mysqlprop>
                        props>
                    property>
                bean>
            array>
        property>

        
        

        
        

        
        

    bean>

    
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.atguigu.dao"/>
    bean>
    
    

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <tx:annotation-driven transaction-manager="transactionManager"/>
beans>

7.编写dao层接口

//将dao层加入到IOC容器管理
@Repository
public interface BookMapper {

//    使用@Insert等注解代替mapper.xml的映射文件
//    新增一个对象
    @Insert("insert into books(bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail})")
    int addBook(Books book) ;

//    根据id删除一个对象
    @Delete("delete from books where bookID=#{bookID}")
    int deleteBookById(int id);

//    修改对象信息
    @Update("update books set bookName = #{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID}")
    int updateBook(Books book);

//    根据id查询一个对象
    @Select("select * from books where bookID=#{bookID}")
    Books queryBookById(int id);

//    查询所有对象
    @Select("select * from books")
    List<Books> queryAll();
}

8.编写service层接口和实现类

8.1service层接口

public interface BookService {

    int addBook(Books book);

    int deleteBookById(Integer id);

    int updateBook(Books book);

    Books queryBookById(Integer id);

    PageInfo<Books> getPageInfo(Integer pageNo);
}

8.2service层接口的实现类

@Service  //将service层加入到IOC容器中管理
@Transactional  //开启事务
public class BookServiceImpl implements BookService {

    @Autowired  //自动注入bookMapper属性
    private BookMapper bookMapper;

    @Override
    public int addBook(Books book) {
        return bookMapper.addBook(book);
    }

    @Override
    public int deleteBookById(Integer id) {
        return bookMapper.deleteBookById(id);
    }

    @Override
    public int updateBook(Books book) {
        return bookMapper.updateBook(book);
    }

    @Override
    @Transactional(readOnly = true) //表示只读
    public Books queryBookById(Integer id) {
        return bookMapper.queryBookById(id);
    }

    @Override
    @Transactional(readOnly = true)  //表示只读
    public PageInfo<Books> getPageInfo(Integer pageNo) {
        // 1、确定每页显示数据的条数
        int pageSize = 4;
        // 2、设定分页数据:开启分页功能。开启后,后面执行的 SELECT 语句会自动被附加 LIMIT 子句,
        // 而且会自动查询总记录数
        PageHelper.startPage(pageNo, pageSize);
        // 3、正常执行查询
        List<Books> bookList = bookMapper.queryAll();
        // 4、封装为 PageInfo 对象返回
        return new PageInfo<>(bookList);
    }
}

9.编写测试类测试spring-mybatis整合

//通过注解来加载Spring上下文从而能够获取spring容器中的对象(Junit5用法)
@SpringJUnitConfig(locations = {"classpath:spring-mybatis.xml"})
public class SSMTest {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private SqlSessionFactory sqlSessionFactory ;

    @Autowired
    private BookMapper bookMapper ;

    @Autowired
    private BookService bookService ;

    //测试数据库是否正常连接
    @Test
    public void test01DataSource() throws SQLException {
        System.out.println("dataSource = " + dataSource);
        System.out.println("dataSource.getConnection = " + dataSource.getConnection());
    }

    //测试sqlSessionFactory对象是否创建成功
    @Test
    public void test02SqlSessionFactory(){
        System.out.println("sqlSessionFactory = " + sqlSessionFactory);
    }

    //测试dao层功能是否正常
    @Test
    public void test03BookMapper(){
        List<Books> books = bookMapper.queryAll();
        System.out.println("books = " + books);
    }

    //测试service层功能是否正常
    @Test
    public void test04BookService(){
        PageInfo<Books> pageInfo = bookService.getPageInfo(1);
        System.out.println("pageInfo = " + pageInfo);
    }
}

10.加入spring-mvc的配置文件


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    
    <bean id="thymeleafViewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <property name="suffix" value=".html"/>
                        <property name="characterEncoding" value="UTF-8"/>
                        <property name="templateMode" value="HTML5"/>
                    bean>
                property>
            bean>
        property>
    bean>

    

    
    <context:component-scan base-package="com.atguigu" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>

    
    <mvc:annotation-driven/>

    
    <mvc:default-servlet-handler/>

    
    <mvc:view-controller path="/" view-name="index"/>

    
    <mvc:view-controller path="/add/book/page" view-name="book-add"/>

beans>

11.编写web.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 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

  
  
  
  
  
  

  
  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      
      <param-value>classpath:spring-mvc.xml,classpath:spring-mybatis.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

  
  <filter>
    <filter-name>characterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
    <init-param>
      <param-name>forceRequestEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
    <init-param>
      <param-name>forceResponseEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>characterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  <filter>
    <filter-name>HiddenHttpMethodFilterfilter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  
web-app>

12.编写静态资源,引入Vue.js

vue.js

13.编写controller层控制器方法

//将控制层加入到IOC容器管理
@Controller
public class BookHandler {

    //自动注入bookService属性
    @Autowired
    private BookService bookService;

    //根据id删除一个对象,携带当前页的页码
    @DeleteMapping("/remove/book/{bookID}/{pageNo}")
    public String removeBook(
            @PathVariable("bookID") Integer bookID,
            @PathVariable("pageNo") Integer pageNo){
        bookService.deleteBookById(bookID);
        //重定向到图书列表页面
        return "redirect:/get/page/" + pageNo;
    }

    //新增一个对象
    @PostMapping("/save/book")
    public String saveBook(Books book){
        bookService.addBook(book);
        //Integer.MAX_VALUE表示非常大的数据,结合配置PageHelper时指定的reasonable可以直接前往最后一页
        return "redirect:/get/page/" + Integer.MAX_VALUE;
    }

    //根据id获得一个对象,携带当前页的页码
    @GetMapping("/edit/book/page/{bookID}/{pageNo}")
    public String editBookPage(
            @PathVariable("bookID") Integer bookID,
            @PathVariable("pageNo") Integer pageNo,
            Model model){
        Books book = bookService.queryBookById(bookID);
        //将获得的对象放入域对象中,用于表单的回显
        model.addAttribute("book",book);
        //重定向到修改图书页面
        return "book-edit";
    }

    //修改一个用户,提交修改表单
    @PutMapping("/update/book")
    //表单隐藏域中携带当前页的页码
    public String updateBook(@RequestParam("pageNo") Integer pageNo,Books book){
        bookService.updateBook(book);
        //重定向到图书列表页面
        return "redirect:/get/page/" + pageNo;
    }

    //查询所有图书
    @RequestMapping("/get/page/{pageNo}")
        public String getPage(@PathVariable("pageNo") Integer pageNo, Model model) {
            // PageInfo 对象封装了和分页相关的所有信息
            PageInfo<Books> pageInfo = bookService.getPageInfo(pageNo);
            // 将 PageInfo 对象存入模型
            model.addAttribute("pageInfo", pageInfo);
            //跳转图书展示页面
            return "book-list-pageable";
    }
}

14.编写页面

14.1首页 index.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页title>
head>
<body style="text-align: center">
    <a th:href="@{/get/page/1}">显示分页图书列表a>
body>
html>

14.2显示图书列表页面 book-list-pageable.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>图书列表页面title>
    <style type="text/css">
        table {
            border-collapse: collapse;
            margin: 0px auto 0px auto;
        }
        table th,td {
            border: 1px solid black;
            text-align: center;
        }
    style>
    <script type="text/javascript" th:src="@{/script/vue.js}">script>
head>
<body>

<table id="dataTable">

    <tr>
        <th>图书IDth>
        <th>图书名称th>
        <th>图书数量th>
        <th>图书详情th>
        <th>删除th>
        <th>更新th>
    tr>

    <tbody th:if="${#lists.isEmpty(pageInfo)}">
    <tr>
        <td colspan="6">抱歉!没有查询到数据!td>
    tr>
    <tr>
        <td colspan="5">
            <a th:href="@{/add/book/page}">添加图书a>
        td>
    tr>
    tbody>

    <tbody th:if="${not #lists.isEmpty(pageInfo)}">

    
    <tr th:each="book : ${pageInfo.list}">
        <td th:text="${book.bookID}">图书IDtd>
        <td th:text="${book.bookName}">图书名称td>
        <td th:text="${book.bookCounts}">图书数量td>
        <td th:text="${book.detail}">图书详情td>
        <td><a th:href="@{/remove/book/}+${book.bookID}+'/'+${pageInfo.pageNum}" @click="doConvert">删除a>td>
        <td><a th:href="@{/edit/book/page/}+${book.bookID}+'/'+${pageInfo.pageNum}">更新a>td>
    tr>

    <tr>
        <td colspan="6"><a th:href="@{/add/book/page}">添加图书a>td>
    tr>
    tbody>
table>

<div align="center">
    <span th:if="${pageInfo.hasPreviousPage}">
        <a th:href="@{/get/page/1}">首页a>
        <a th:href="@{/get/page/}+${pageInfo.prePage}">上一页a>
        span>

    <span th:each="navigator : ${pageInfo.navigatepageNums}">

         
        <a th:if="${navigator != pageInfo.pageNum}"
           th:href="@{/get/page/}+${navigator}"
           th:text="'['+${navigator}+']'">a>

        
        <span th:if="${navigator == pageInfo.pageNum}" th:text="'['+${navigator}+']'">span>
        span>

    <span th:if="${pageInfo.hasNextPage}">
        <a th:href="@{/get/page/}+${pageInfo.nextPage}">下一页a>
        <a th:href="@{/get/page/}+${pageInfo.pages}">最后一页a>
        span>

    <span th:text="${pageInfo.pageNum}+'/'+${pageInfo.pages}">span>
div>


<form id="convertForm" method="post">
    <input type="hidden" name="_method" value="delete"/>
form>

<script>
    new Vue({
        el:"#dataTable",
        methods:{
            doConvert:function (event) {

                // 1.根据 id 值查询到通用表单的元素对象
                var convertFormEle = document.getElementById("convertForm");

                // 2.将当前超链接的 href 属性值赋值给通用表单的元素对象的 action 属性
                convertFormEle.action = event.target.href;

                // 3.提交通用表单
                convertFormEle.submit();

                // 4.取消超链接控件的默认行为
                event.preventDefault();
            }
        }
    });
script>

body>
html>

14.3添加图书页面 book-add.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加图书页面title>
head>
<body>
<form th:action="@{/save/book}" method="post">
    图书名称:<input type="text" name="bookName" /><br/>
    图书数量:<input type="text" name="bookCounts" /><br/>
    图书详情:<input type="text" name="detail" /><br/>
    <button type="submit">保存button>
form>
body>
html>

14.4修改图书页面 book-edit.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>修改图书页面title>
head>
<body>
    <form th:action="@{/update/book}" method="post">

        
        <input type="hidden" name="_method" value="PUT" />

        
        <input type="hidden" name="bookID" th:value="${book.bookID}" />

        
        <input type="hidden" name="pageNo" th:value="${pageNo}" />

        图书名称:<input type="text" name="bookName" th:value="${book.bookName}"/><br/>
        图书数量:<input type="text" name="bookCounts" th:value="${book.bookCounts}"/><br/>
        图书详情:<input type="text" name="detail" th:value="${book.detail}"/><br/>
        <button type="submit">保存button>
    form>
body>
html>

你可能感兴趣的:(ssm框架整合,java,spring)