关于springboot:SpringBootMyBatisSpringThymeleaf

8次阅读

共计 7860 个字符,预计需要花费 20 分钟才能阅读完成。

SpringMVC 简介

背景剖析

在大型软件系统设计时,业务个别会绝对简单,如果所有业务实现的代码都纠缠在一起,会呈现逻辑不清晰、可读性差,保护艰难,改变一处就牵一发而动全身等问题。为了更好解决这个问题就有了咱们当初常说的分层架构设计。

MVC 是什么

MVC 是一种软件架构设计思维, 基于 MVC 架构将咱们的应用软件进行分层设计和实现, 例如能够分为视图层(View), 管制层(Controller), 模型层(Model), 通过这样的分层设计让咱们程序具备更好的灵活性和可可扩展性. 因为这样能够将一个简单应用程序进行简化, 实现各司其职, 各尽所能. 比拟适宜一个大型利用的开发.

SpringMVC 概述

Spring MVC 是 MVC 设计思维在 Spring 框架中的一种实现,基于这样的思维 spring 框架设计了一些相干对象,用于更好的基于 MVC 架构解决申请和响应,其繁难架构如图所示:

其中:
1)DispatcherServlet 是客户端所有申请解决的入口, 负责申请转发。
2)RequestMapping 负责存储申请 url 到后端 handler 对象之间的映射。
3)Handler 用于解决 DispatcherServlet 对象转发过去的申请数据。
4)ViewResolver 负责解决所有 Handler 对象响应后果中的 view。

基于 Spring,MyBatis,SpringBoot,Thymeleaf 技术实现商品模块的增删改查操作

第一步:创立 springboot 我的项目 10-springboot-goods

第二步:增加依赖

第三步:配置文件初始化

#server
server.port=1314
#spring datasource
spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=1234
#spring mybatis
mybatis.mapper-locations=classpath:/mapper/*/*.xml
#spring thymeleaf
spring.thymeleaf.prefix=classpath:/templates/pages/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
#spring logging
#logging.file.path=d:/logs/
logging.level.com.cy=debug
management.endpoints.web.exposure.include=*

我的项目 API 架构设计

其 API 架构设计,如图所示:

商品 CRUD 业务实现

业务时序剖析

查问所有商品信息,其业务时序剖析,如图所示:

第一步:定义 Goods 对象,封装查问到的对象

package com.cy.pj.goods.pojo;
import java.util.Date;
/**
 * 用来封装商品
 */
public class Goods {
    private Long id;//id bigint primary key auto_increment
 private String name;//name varchar(100) not null
 private String remark;//remark text
 private Date createdTime;//createdTime datetime
 public Long getId() {return id;}
    public void setId(Long id) {this.id = id;}
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public String getRemark() {return remark;}
    public void setRemark(String remark) {this.remark = remark;}
    public Date getCreatedTime() {return createdTime;}
    @Override
 public String toString() {
        return "Goods{" +
                "id=" + id +
                ", name='" + name + '''+", remark='"+ remark +''' +
                ", createdTime=" + createdTime +
                '}';
 }
}

第二步:Dao 接口办法及映射定义

package com.cy.pj.goods.dao;
import java.util.List;
import org.apache.ibatis.annotations.*;
import com.cy.pj.goods.pojo.Goods;
/**
 * 商品数据逻辑对象,负责商品模块的数据拜访逻辑的实现
 */
@Mapper
public interface GoodsDao {@Update("update tb_goods set name=#{name},remark=#{remark} where id=#{id}")
    int updateGoods(Goods entity);
 @Select("select * from tb_goods where id=#{id}")
    Goods findById(Integer id);
 @Insert("insert into tb_goods(name,remark,createdTime) values(#{name},#{remark},now())")
    int insertGoods(Goods entity);
 /**
 * 基于 id 进行删除
 * @param id
 * @return
 */
 @Delete("delete from tb_goods where id=#{id}")
    int deleteById(Integer id);
 /**
 * 查问所有的商品信息
 * @return 所有的商品
 * mybatis 框架中定义 sql 映射有两种形式:* 1,注解形式(实现简略的 sql 映射)* 2,应用 XML 形式(实现简单的 sql 映射)*/
 @Select("select * from tb_goods")
    List<Goods> findGoods();}

第三步:Service 接口办法定义及实现

GoodsService 接口

package com.cy.pj.goods.service;
import com.cy.pj.goods.pojo.Goods;
import java.util.List;
/**
 * 用来定义商品业务逻辑操作的接口
 */
public interface GoodsService {int updateGoods(Goods entity);
 Goods findById(Integer id);
 int saveGoods(Goods entity);
 int deleteById(Integer id);
 List<Goods> findGoods();}

GoodsService 接口实现类 GoodsServiceImpl 定义及办法实现

package com.cy.pj.goods.service;
import com.cy.pj.goods.dao.GoodsDao;
import com.cy.pj.goods.pojo.Goods;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GoodsServiceImpl implements GoodsService {private static final Logger log=LoggerFactory.getLogger(GoodsServiceImpl.class);
 @Autowired
 private GoodsDao goodsDao;
 @Override
 public int updateGoods(Goods entity) {// 对于 update 操作,参数 entity 中须要有一个 id 值
 return goodsDao.updateGoods(entity);
 }
    @Override
 public Goods findById(Integer id) {return goodsDao.findById(id);// 未来还能够将查问到的后果在业务逻辑层存储到 cache
 }
    @Override
 public int saveGoods(Goods entity) {return goodsDao.insertGoods(entity);
 }
    @Override
 public int deleteById(Integer id) {int rows=goodsDao.deleteById(id);
 return rows;
 }
    @Override
 public List<Goods> findGoods() {long t1=System.currentTimeMillis();
 List<Goods> list=goodsDao.findGoods();
 long t2=System.currentTimeMillis();
 log.info("findGoods time-> {}", t2-t1);//{}为占位符好
 return list;
 }
}

第四步:Controller 对象办法定义及实现

定义 GoodsController 类,

package com.cy.pj.goods.controller;
import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/goods/")
public class GoodsController {
    @Autowired
 private GoodsService goodsService;
 @PostMapping("doUpdateGoods")
    public String doUpdateGoods(Goods entity){// 用 pojo 对象接管客户端参数
 goodsService.updateGoods(entity);
 return "redirect:/goods/doGoodsUI";
 }
    @RequestMapping("doFindById/{id}")
    public String doFindById(@PathVariable Integer id,Model model){Goods goods=goodsService.findById(id);
 model.addAttribute("g", goods);
 return "goods-update";
 }
    @RequestMapping("doSaveGoods")
    public String doSaveGoods(Goods entity){// 用 pojo 对象接管客户端参数
 goodsService.saveGoods(entity);
 return "redirect:/goods/doGoodsUI";
 }
    /**
 * 返回商品增加页面
 * @return
 */
 @RequestMapping("doGoodsAddUI")
    public String doGoodsAddUI(){return "goods-add";}
    @RequestMapping("doDeleteById/{id}")//rest 格调(软件架构编码格调)url
 public String doDeleteById(@PathVariable Integer id){//@PathVariable 形容参数时示意参数的值来自 url
 goodsService.deleteById(id);
 return "redirect:/goods/doGoodsUI";//redirect 示意重定向(客户端再次向服务端发申请)
 }
//    @RequestMapping("doDeleteById")
//    public String doDeleteById(Integer id){//        goodsService.deleteById(id);
//        return "redirect:/goods/doGoodsUI";//redirct 示意重定向(客户端再次向服务端发申请)//    }
 @RequestMapping("doGoodsUI")
    public String doGoodsUI(Model model){List<Goods> goodsList=goodsService.findGoods();
 model.addAttribute("goodsList", goodsList);
 return "goods";//Viewname
 // 返回值会交给 DispatcherServ
 // let 进行解决
 //DispatcherServlet 会调用 ViewResolver 进行视图解析(view+model)
 // 最初 DispatcherServlet 将解析后果响应到页面上
 }
}

第五步:Goods 商品列表页面设计及实现

在 templates/pages 目录中增加 goods.html 页面,并在 body 中增加 html 元素,在运行外部应用 thymeleaf 标签属性获取数据,代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<table width="50%">
 <a th:href="@{/goods/doGoodsAddUI}"> 增加商品 </a>
 <thead> <th>id</th>
 <th>name</th>
 <th>remark</th>
 <th>createdTime</th>
 <th colspan="2">operation</th>
 </thead> <tbody> <tr th:each="g:${goodsList}">
 <td th:text="${g.id}">1</td>
 <td th:text="${g.name}">MySQL</td>
 <td th:text="${g.remark}">DBMS</td>
 <td th:text="${#dates.format(g.createdTime,'yyyy/MM/dd HH:mm')}">2020/07/03</td>
 <td><a th:href="@{/goods/doDeleteById/{id}(id=${g.id})}">delete</a></td>
 <td><a th:href="@{/goods/doFindById/{id}(id=${g.id})}">update</a></td>
 </tr> </tbody></table>
</body>
</html>

goods-adds.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <!--
 ul li:后辈选择器,ul 里所有的 li 元素,包含 ol 里的 li ; ul>li:子代选择器,下一级的 DOM 节点,不包含 ol 里的 li。ul>ol>li:子代选择器必须一代接一代。-->
 <style>
 ul>li{list-style-type: none;}
    </style>
</head>
<body>
<div>
<h1>the goods add pages</h1>
 <form th:action="@{/goods/doSaveGoods}" method="post">
 <ul> <li>name</li>
 <li><input type="text" name="name"></li>
 <li>remark</li>
 <li><textarea rows="3" cols="50" name="remark"></textarea></li>
 <li><input type="submit" value="Save Goods"></li>
 </ul> </form>
</div>
</body>
</html>

goods-update.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <!--
 ul li:后辈选择器,ul 里所有的 li 元素,包含 ol 里的 li ; ul>li:子代选择器,下一级的 DOM 节点,不包含 ol 里的 li。ul>ol>li:子代选择器必须一代接一代。-->
 <style>
 ul>li{list-style-type: none;}
    </style>
</head>
<body>
<div>
<h1>the goods update pages</h1>
 <form th:action="@{/goods/doUpdateGoods}" method="post">
 <ul> <li><input type="hidden" name="id" th:value="${g.id}"></li>
 <li>name</li>
 <li><input type="text" name="name" th:value="${g.name}"></li>
 <li>remark</li>
 <li><textarea rows="3" cols="50" name="remark" th:text="${g.remark}"></textarea></li>
 <li><input type="submit" value="Update Goods"></li>
 </ul> </form>
</div>
</body>
</html>

thymeleaf 是一种模板引擎,此引擎以 html 为模板,能够增加自定义标签属性,能够将服务端 model 中数据填充在页面上,而后实现与用于交互。其官网为 thymeleaf.org

Goods 页面上数据出现剖析:


第六步:启动服务器进行测试
http://localhost:1314/goods/doGoodsUI


正文完
 0