0
点赞
收藏
分享

微信扫一扫

视图解析

  • thymeleaf语法:

${...}         获取请求域、session域、对象等值       

session.setAttribute("loginUser",user); # 向HttpSession中添加数据

session.getAttribute("loginUser"); # 获取HttpSession中的数据

model.addAttribute("msg","账号密码错误"); # 向Model中添加数据

request.setAttribute("msg","成功了..."); # 向HttpServletRequest中添加数据

request.getAttribute("hello"); # 获取HttpServletRequest中的数据

response.addCookie(cookie); # 向HttpServletResponse中添加数据

map.put("hello","world666"); # 向Map集合中添加数据


@{...} 生成链接

th:text="${msg}"

th:action="@{/login}" # aciton="/login"

th:href="@{/basic_table}" # 引入html

th:href="@{/css/style.css}" # 引入css

[[${session.loginUser.userName}]] # 控制层session.setAttribute("loginUser",user);前端获取session中数据,userName是实体类属性

th:href="@{/} # @GetMapping(value = {"/","/login"}) 控制层配置的路由,所以这里是跳到登录页面

  • thymeleaf使用

引入thymeleaf依赖(场景)

页面放在templates路径下,后缀为html,并加上名称空间 xmlns:th="http://www.thymeleaf.org" 到html标签

视图解析_添加数据

  • 案例:发送一个请求,跳转到success页面,将后端model中的数据,动态赋值给thymeleaf模板页面

# 控制层处理请求:
@Controller
public class ViewTestController {
@GetMapping("/atguigu")
public String atguigu(Model model){
//model中的数据会被放在请求域中 request.setAttribute("a",aa)
model.addAttribute("msg","你好 guigu");
model.addAttribute("link","http://www.baidu.com");
return "success";
}
}

# 前端页面动态取值:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${msg}">哈哈</h1>
<h2>
<a href="www.atguigu.com" th:href="${link}">去百度</a> <br/>
<a href="www.atguigu.com" th:href="@{/link}">去百度2</a>
</h2>
</body>
</html>

# 只有前端时,和动态取值后的页面是不同的

视图解析_html_02

视图解析_html_03

  • 配置文件

# yml中的配置:此时所有请求必须是http://localhost:8080/world/atguigu 才能请求成功
server:
servlet:
context-path: /world

# properties中的配置方式
spring.thymeleaf.cache=false # 禁用缓存
spring.thymeleaf.suffix=.html # 模板后缀名
spring.mvc.view.prefix=classpath:/templates/ # 模板路径

#yml配置方式
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
content-type: text/html
mode: HTML5



举报

相关推荐

0 条评论