Spring Boot整合Spring MVC(PROJECT01_DAY04_02)

3.2 初始配置

3.1 添加Spring MVC依赖

编辑pom.xml文件,添加Web依赖,Thymeleaf依赖,代码如下:
Web依赖(提供了Spring MVC核心API,同时会嵌入一个Tomcat服务器)

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

Thymeleaf依赖(提供了一个视图解析器对象以及数据绑定机制)

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

其中: Spring Web Starter 提供Spring MVC 依赖支持,并会自动添加一个Tomcat依赖,作为嵌入式Web服务器使用 . Thymeleaf是一个html模板引擎,提供了与Spring MVC进行整合的API,可作为MVC架构中Web应用的View层。

3.2 配置Spring MVC 核心对象

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

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

说明:要基于配置在src/main/resources目录下创建templates/pages目录

3.3 Spring MVC 进行入门实践

第一步:编写GoodsController类并将其交给Spring管理。这样的Controller在SpringMVC 规范中通常称之为Handler(处理器),我们在企业中有时也会将此对象理解为一个后端控制器。

package com.cy.pj.goods.controller;
@Controller    
@RequestMapping("/goods/")//可以不写吗?
public class GoodsController {
    @RequestMapping("doGoodsUI")//作用是什么?和上面的@RequestMapping 注解有什么关系吗?
	public String doGoodsUI() {
           return "goods";//返回给调用方,这里是DispatcherServlet
           				  //DispatcherServlet会将goods字符串交给视图解析器,thymeleaf 中的视图解析器会对goods字符串添加前缀和后缀
	}
}

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

第三步:启动服务器(默认项目嵌入的是Tomcat),打开浏览器进行访问测试。

课堂练习:
练习一:将数据库中的商品数据查询出来展示到页面上。
练习二:基于 id 删除商品库中的商品信息。
练习三:将页面用户输入的商品信息写入到数据库。

练习总结:
API应用设计,如图-16所示:
在这里插入图片描述
图-16

 //http://localhost:8080/goods/doGoodsUI
@RequestMapping("doGoodsUI")
public String doGoodsUI(Model model) {//model为Spring MVC中用于存储数据的一个对象,底层为map
	List<Goods> list = goodsService.findGoods();
	model.addAttribute("goods", list);
	return "goods";//viewName,返回给调用方,在这里是前端控制器
				   //前端控制器会将goods字符串交给视图解析器(thymeleaf提供)
				   //thymeleaf中的视图解析器会对goods字符串添加前缀和后缀
}

用 Thymeleaf 来对对象进行解析的话,如何来做呢?

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>This is Goods Page</h1>
	<div>
			<table>
				<thead>
					<tr>
						<th>Name</th>
						<th>Remark</th>
						<th>CreatedTime</th>
					</tr>
				</thead>
				<tbody>
					<!-- th:each th:text ${} 由thymeleaf引擎定义的 -->
					<tr th:each="g: ${goods}">
						<td th:text="${g.name}"></td>
						<td th:text="${g.remark}"></td>
						<td th:text="${#dates.format(g.CreatedTime, 'yyyy/MM/dd HH:mm:ss')}"></td>
					</tr>
				</tbody>
			</table>
	</div>
</body>
</html>
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值