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>