thymeleaf使用
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.页面文件放在resources下templates目录下,.html类型的文件
3.页面开发:
<!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> //这样会获取到/link
</h2>
</body>
</html>
th: 获取请求域中的值
4.controller层:
@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";
}
}
视图解析
视图处理方式:转发 重定向 自定义视图
return 了一个字符串
会由这个返回值处理器处理
1.然后将返回的地址字符串存到在 ModelAndViewContainer中,包括数据和视图地址。
划线处是判断是否为重定向,是的话就设置重定向模式为true。
2.如果方法的参数是一个自定义类型对象(从请求参数中确定的),把他重新放在 ModelAndViewContainer
3、任何目标方法执行完成以后都会返回 ModelAndView(数据和视图地址)。
4、processDispatchResult 处理派发结果(页面改如何响应)
(1)、render(mv, request, response); 进行页面渲染逻辑
1)根据方法的String返回值得到 View 对象【定义了页面的渲染逻辑】其中有model request等
所有的视图解析器尝试是否能根据当前返回值得到View对象
视图解析器:作用就是得到view对象 此处用的是0. ContentNegotiationViewResolver 内容协商视图解析器。实际用的是Thymeleaf视图解析器
ContentNegotiationViewResolver 里面包含了下面所有的视图解析器,内部还是利用下面所有视图解析器得到视图对象。
得到了 redirect:/main.html --> Thymeleaf new RedirectView()
然后
view.render(mv.getModelInternal(), request, response); 视图对象调用自定义的render进行页面渲染工作
RedirectView 如何渲染【重定向到一个页面】
1、获取目标url地址
2、response.sendRedirect(encodedURL);
视图解析
返回值以 forward: 开始: new InternalResourceView(forwardUrl); --> 转发 request.getRequestDispatcher(path).forward(request, response);
返回值以 redirect: 开始: new RedirectView() --》 render就是重定向
返回值是普通字符串: new ThymeleafView()—>