目录
1、静态资源访问
Spring Boot 默认会挨个从META/resources > resources > static > public 里面找是否存在相应的资源,如果有则直接返回
1.1 默认配置
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources
举例:在src/main/resources/目录下创建public,在该位置创建public.html文件。启动程序后,尝试访问http://127.0.0.1:8888/study/public.html。
1.2 修改静态资源文件配置
增加一个image目录
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/image
直接访问增加的image目录的的图片:
2、请求转发和重定向
重定向redirect
@RequestMapping(path="/view/index_redirect")
public String getPage_redirect() {
//return “redirect:/page/view/index_forword”;
return “redirect:/public.html”;
}
转发forward
@RequestMapping(path="/view/index_forword")
public String getPage_forword() {
//return “forward:/page/view/index_redirect”;
return “forward:/public.html”;
}
3、渲染Web页面
3.1 整合thymeleaf模板引擎
3.1.1 Thymeleaf 常用的表达式、标签和函数
1.常用表达式
- ${...}变量表达式。
- * { .. . } 选择表达式。
- #{...}消息文字表达式。
- @ {} 链接url 表达式。
- #maps 工具对象表达式。
2.常用标签
- th:action 定义后台控制器路径。
- th:each 1,盾环语-句。
- th:field 表单字段绑定。
- th:href 定义超链接。
- th:id div 标签中的ID 声明,类似HTML 标签中的归属性。
- th:if 条件判断语句。
- th:include 布局标签,替换内容到引入文件。
- th :企agment 布局标签,定义一个代码片段,方便其他地方引用。
- th:object 替换对象。
- th:src 图片类地址引入。
- th:text 显示文本。
- th:value 属性赋值。
3.常用函数
- #dates 日期函数。
- #lists 列表函数。
- #arrays 数组函数。
- #strings 字符串函数。
- #numbers 幸生字函捷生。
- #ca lendars 日历函数。
- #objects 对象函数。
- #bools 逻辑函数。
3.1.2 整合Thymeleaf的简单demo
- 第一步:添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 第二步:添加配置(可不配置,全都按照默认配置)
###ThymeLeaf配置
#模板的模式,支持 HTML, XML TEXT JAVASCRIPT
spring.thymeleaf.mode=HTML5
#编码 可不用配置
spring.thymeleaf.encoding=UTF-8
#开发配置为false,避免修改模板还要重启服务器
spring.thymeleaf.cache=false
#配置模板路径,默认是templates
spring.thymeleaf.prefix=classpath:/templates/
#配置模板文件的后缀
spring.thymeleaf.suffix=.html
- 第三步:编写模板和Controller接口
@RequestMapping(path="/view/index3")
public ModelAndView getPage_3() {
ModelAndView model = new ModelAndView();
model.setViewName("page/user");
model.addObject("name", "小明");
return model;
}
模本文件的存放路径一定要和spring.thymeleaf.prefix一致,默认是
classpath:/templates/
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
page/page目录下: username-><span th:text="${name}"></span>
</body>
</html>
- 第四步:测试访问
可以看到模板中的<span th:text="${name}"></span>
被替换为了小明
4、项目git地址
spring-boot2-http