SpringBoot整合MVC和Mybatis

2021-03-27

目录:
一 SpringBoot 整合 SpringMVC
二 SpringBoot 基于 SpringMVC 和 Mybatis 的简单增删改查案例

一 SpringBoot 整合 SpringMVC

第一步:添加MVC的依赖

添加Spring Web依赖
<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
</dependency>

添加Thymeleaf依赖(提供了一个视图解析器对象以及数据绑定机制)
Web依赖(提供了Spring MVC核心API , 同时会嵌入一个Tomcate服务器)

其中 :Spring Web Starter 提供了Soring MVC依赖支持,提供了Spring MVC核心API。会自动添加一个tomcate依赖,作为嵌入式web服务器使用。
Thymeleaf是一个html模板引擎,提供了于SpringMVC进行整合的API,可作为MVC框架中Web应用的View层。

说明:SpringBoot不在支持jsp 若要使用jsp需要在xml中进行相关配置

第二步:配置Spring MVC核心对象

1:现在 src/main/resources目录下创建templates/pages目录

2:在application.properties文件中添加视图解析器配置(加入没有默认也会配置,在默认配置中prefix默认值为classpath:/templates/,后缀默认为 .html)

spring.thymeleaf.prefix=classpath:/templates/pages/
spring.thymeleaf.suffix=.html

在这里插入图片描述

第三步:创建Controller类

编写 XxxController(GoodsController)类并将其交给spring来管理。这样的Controller在SpringMVC规范中通常称之为Handler(处理器-Model),我们在企业中有时也会将此对象理解为一个后端控制器(从严谨性上来讲不够规范)
在这里插入图片描述

package com.cy.pj.goods.controller;
@Controller
	
@RequestMapping("/goods/")
public class GoodsController {
     @RequestMapping("doGoodsUI")
public String doGoodsUI() {
	   return "goods";
}
}

第四步:需要在/tmplates/pages/目录下创建goods.html

第五步:启动服务器(默认项目嵌入的是Spring web Starter 提供的默认服务器),打开浏览器进行访问测试

SpringBoot 整合 Mybatis+MVC 并运用 Thymeleaf模板引擎 实现从数据库查询相关信息显示在页面上 简单项目案例

以STS软件为例

第一步:导入将sql文件导入数据库

打开dos命令窗口导入打开MySQL导入sql文件
在这里插入图片描述
代码如下

1:登录mysql

mysql –uroot –proot

2:设置客户端控制台编码(MySql客户端)方式

set names utf8;

3:执行goods.sql文件

source d:/goods.sql

sql文件如下

drop database if exists dbgoods;
create database dbgoods default character set utf8;
use dbgoods;
create table tb_goods(
     id bigint primary key auto_increment,
     name varchar(100) not null,
     remark text,
     createdTime datetime not null
)engine=InnoDB;
insert into tb_goods values (null,'java','very good',now());
insert into tb_goods values (null,'mysql','RDBMS',now());
insert into tb_goods values (null,'Oracle','RDBMS',now());
insert into tb_goods values (null,'java','very good',now());
insert into tb_goods values (null,'mysql','RDBMS',now());
insert into tb_goods values (null,'Oracle','RDBMS',now());
insert into tb_goods values (null,'java','very good',now());
insert into tb_goods values (null,'mysql','RDBMS',now());
insert into tb_goods values (null,'Oracle','RDBMS',now());
insert into tb_goods values (null,'java','very good',now());
insert into tb_goods values (null,'mysql','RDBMS',now());
insert into tb_goods values (null,'Oracle','RDBMS',now());



第二步:创建工程

在这里插入图片描述

第三步:添加相关依赖

导入Mybatis 相关依赖
1 mysql驱动包

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>

2 spring jdbc 依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

3 mybatis starter依赖

<dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>2.1.1</version>
</dependency>
注意:mybatis starter 依赖的版本可能不会自动给,需要手动添加!!!

导入 MVC相关依赖
1 Web依赖

<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2 Thymeleaf依赖

<dependency>
	   <groupId>org.springframework.boot</groupId>
	   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

第四步:application.propertis配置文件中添加配置

在这里插入图片描述

代码如下

# service
service.port=80
service.servlet.context.path=/
spring.main.banner-mode=off

# spring datasource
# serverTimezone=GMT%2B8 为设置时区为东八区
# characterEncoding=utf8设置编码格式为utf-8
spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8
# 自己数据库的用户名
spring.datasource.username=root
# 自己数据库的密码
spring.datasource.password=root

# spring mybatis
mybatis.mapper-locations=classpath:/mapper/*/*.xml

# spring thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/pages/
spring.thymeleaf.suffix=.html

# spring log
logging.level.com.cy=debug

在application.properties文件中添加视图解析器配置(假如没有配置也会默认配置,在默认配置中prefix默认值为classpath:/templates/,后缀默认为.html)

第五步 创建Pojo类

在这里插入图片描述
代码如下

package com.cy.goods.Pojo;                                                                                                                                    
                                                                                                                                                              
import java.sql.Date;                                                                                                                                         
                                                                                                                                                              
public class Goods {                                                                                                                                          
	private Integer id;                                                                                                                                       
	private String name;                                                                                                                                      
	private String remark;                                                                                                                                    
	private Date createdTime;                                                                                                                                 
	                                                                                                                                                          
	public Goods() {                                                                                                                                          
		super();                                                                                                                                              
	}                                                                                                                                                         
	                                                                                                                                                          
	public Goods(Integer id, String name, String remark, Date createdTime) {                                                                                  
		super();                                                                                                                                              
		this.id = id;                                                                                                                                         
		this.name = name;                                                                                                                                     
		this.remark = remark;                                                                                                                                 
		this.createdTime = createdTime;                                                                                                                       
	}                                                                                                                                                         
                                                                                                                                                              
	public Integer getId() {                                                                                                                                  
		return id;                                                                                                                                            
	}                                                                                                                                                         
                                                                                                                                                              
	public void setId(Integer 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;                                                                                                                                   
	}                                                                                                                                                         
                                                                                                                                                              
	public void setCreatedTime(Date createdTime) {                                                                                                            
		this.createdTime = createdTime;                                                                                                                       
	}                                                                                                                                                         
	                                                                                                                                                          
}                                                                                                                                                             
                                                                                                                                                              

第六步 创建 Dao

在这里插入图片描述

代码如下

package com.cy.goods.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.cy.goods.pojo.Goods;

@Mapper
public interface GoodsDao {
	// 查询全部信息
	@Select("select id,name,remark,createdTime from tb_goods")
	List<Goods> findAllGoods();
	
	// 删除操作
	@Delete("delete from tb_goods where id = #{id}")
	int deleteById(Integer id);
	
	// 添加操作
	@Insert("insert into tb_goods(name,remark,createdTime) value (#{name},#{remark},now())")
	int addGoods(Goods goods);

	//	修改操作
	@Select("select id,name,remark from tb_goods where id=#{id}")
	Goods finGoods(Integer id);
	
	@Update("update tb_goods set name=#{name} , remark=#{remark} where id=#{id}")
	int updateGoods(Goods goods);
	
}


第七步 创建Service

在这里插入图片描述

代码如下

package com.cy.goods.servlet;

import java.util.List;

import com.cy.goods.pojo.Goods;

public interface ServiceGoods {
	// 查询所有
	List<Goods> finAllGoods();
	// 删除操作
	int deleteById(Integer id);
	// 添加操作
	int addGoods(Goods goods);
	// 修改操作
	Goods findGoods(Integer id);
	int updateGoods(Goods goods);
}


第八步 创建ServiceImpl

在这里插入图片描述

代码如下

package com.cy.goods.servlet.servletImpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cy.goods.dao.GoodsDao;
import com.cy.goods.pojo.Goods;
import com.cy.goods.servlet.ServiceGoods;

@Service
public class ServiceGoodsImpl implements ServiceGoods {

	@Autowired
	private GoodsDao goodsDao;
	@Override
	// 查询所有
	public List<Goods> finAllGoods() {
		// TODO Auto-generated method stub
		return goodsDao.findAllGoods();
	}
	// 删除操作
	public int deleteById(Integer id) {
		// TODO Auto-generated method stub
		return goodsDao.deleteById(id);
	}
	// 添加操作
	public int addGoods(Goods goods) {
		// TODO Auto-generated method stub
		return goodsDao.addGoods(goods);
	}
	// 修改操作
	@Override
	public Goods findGoods(Integer id) {
		// TODO Auto-generated method stub
		return goodsDao.finGoods(id);
	}
	@Override
	public int updateGoods(Goods goods) {
		// TODO Auto-generated method stub
		return goodsDao.updateGoods(goods);
	}
}

第九步

创建Controller
在这里插入图片描述

在这里插入图片描述

代码如下

package com.cy.goods.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cy.goods.pojo.Goods;
import com.cy.goods.servlet.ServiceGoods;

@Controller
@RequestMapping("/goods/")
public class GoodsController {
	
	@Autowired
	private ServiceGoods serviceGoods;
// 查询所有
	@RequestMapping("findAllGoods")
	public String findAllGoods(Model model) {
		List<Goods> list = serviceGoods.finAllGoods();
		model.addAttribute("goods", list);
		return "goods";
	}
	
//	删除操作
	@RequestMapping("deleteById")
	public String deleteById(Integer id) {
		serviceGoods.deleteById(id);
		return "redirect:/goods/findAllGoods";
		
	}
// 添加操作
	@RequestMapping("insertGoods")
	public String insertGoods() {
		return "insertGoods";
	}
	
	@RequestMapping("addGoods")
	public String addGoods(Goods goods) {
		serviceGoods.addGoods(goods);
		return "redirect:/goods/findAllGoods";
		
	}
// 修改操作
	@RequestMapping("findGoods")
	public String findGoods(Integer id , Model model) {
		Goods goods = serviceGoods.findGoods(id);
		model.addAttribute("findGoods", goods);
		return "update";
	}
	
	@RequestMapping("updateGoods")
	public String updateGoods(Goods goods) {
		serviceGoods.updateGoods(goods);
		return "redirect:/goods/findAllGoods";
	}
	
}

第十步 创建html

创建 主页面
在这里插入图片描述
对应浏览器显示
在这里插入图片描述

代码如下

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="#" th:href="@{/goods/insertGoods}">添加</a>
	<table>
		<thead>
			<tr>
				<th>id</th>
				<th>name</th>
				<th>date</th>
				<th>operation</th>
			</tr>
		</thead>
		<tbody>
			 <tr th:each="g:${goods}">
          		<td th:text="${g.id}">1</td>  
          		<td th:text="${g.name}">MySQL</td>  
          		<td th:text="${g.remark}">RDBMS</td>  
          		<td th:text="${#dates.format(g.createdTime, 'yyyy/MM/dd HH:mm')}">2020/08/03 16:10</td> 
				<td><a href="#" th:href="@{/goods/deleteById(id=${g.id})}">Delete</a></td>
				<td><a href="#" th:href="@{/goods/findGoods(id=${g.id})}">Update</a>
			</tr>
		</tbody>
	</table>
	</table>
</body>
</html>

创建添加页面
在这里插入图片描述
对应浏览器显示
在这里插入图片描述代码如下

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
ul li {list-style-type: none}
</style>
</head>
<body>
	<form th:action="@{/goods/addGoods}" method="post">
	<ul>
		<li>name:
		<li><input type="text" name="name">
		<li>remark:
		<li><textarea rows="5" cols="30" name="remark"></textarea>
		<li><input type="submit" value="Save">
	</ul>
	</form>
</body>
</html>

创建修改页面
在这里插入图片描述
对应浏览器显示
在这里插入图片描述
代码如下

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
ul li {list-style-type: none}
</style>
</head>
<body>
	<form th:action="@{/goods/updateGoods}" method="post">
	<input type="hidden" name="id" th:value="${findGoods.id}">
	<ul>
		<li>name:
		<li><input type="text" name="name" th:value="${findGoods.name}">
		<li>remark:
		<li><textarea rows="5" cols="30" name="remark" th:text="${findGoods.remark}"></textarea>
		<li><input type="submit" value="Update">
	</ul>
	</form>
</body>
</html>

第十一步 测试

在浏览器输入URL测试
URL 地址:http://localhost:8080/goods/findAllGoods

演示

在这里插入图片描述

每日记录相关学习内容写的不是很好,请多多指教

陕西科技大学镐京学院:攻程狮社团

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值