1.视图解析

视图解析:SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染。


视图解析原理流程

1.目标方法处理的过程中,所有数据都会被放在 ModelAndViewContainer 里面。包括数据和视图地址
view:显示的是要去的页面的地址。同时还有处理过程中的数据。

2.方法的参数是一个自定义类型对象(从请求参数中确定的),把把重新放在 ModelAndViewContainer
请求处理产生的数据都会放在容器中

3.任何目标方法执行完成以后都会返回 ModelAndView(数据和视图地址)

4.processDispatchResult 处理派发结果(页面如何响应)

  • render(mv, request, response); 进行页面渲染逻辑

  • 根据方法的String返回值得到 View 对象(定义了页面的渲染逻辑)

  • 1.所有的视图解析器尝试是否能根据当前返回值得到View对象

  • 2.得到了 redirect:/index.html --> Thymeleaf new RedirectView()

  • 3.ContentNegotiationViewResolver 里面包含了下面所有的视图解析器,内部还是利用下面所有视图解析器得到视图对象。

  • 4.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()

1.模板引擎-Thymeleaf

1.Thymeleaf简介

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.Thymeleaf’s main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.——Link

适合于单体应用,可用于springboot,但性能不是很高。
Thymeleaf官方文档

引入Starter

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

Springboot自动配置好了thymeleaf

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {...
}

自动配好的策略

  • 1.所有thymeleaf的配置值都在 ThymeleafProperties

  • 2.配置好了 SpringTemplateEngine

  • 3.配好了 ThymeleafViewResolver

  • 4.我们只需要直接开发页面

模板放置处和后缀名

public static final String DEFAULT_PREFIX = "classpath:/templates/";//模板放置处
public static final String DEFAULT_SUFFIX = ".html";//文件的后缀名

编写一个控制层:

@Controller
@GetMapping("/atguxiaojie")public String atguxiaojie(Model model){//model中的数据会被放入到请求域中 request.setAttribute("a",aa)model.addAttribute("msg","你好 guxiaojie");model.addAttribute("link","http://www.baidu.com");return "success";}

/templates/success.html:

注意,这里要在html文件中加上名称空间,表示它是一个thymeleaf类模板。

<!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><!--默认去www.atguigu.com地址,真正去的地址由后面的确定--><a href="www.atguigu.com" th:href="${link}">去百度</a><br/><a href="www.atguigu.com" th:href="@{/link}">去百度2</a><br/>
</h2>
</body>
</html>
server:servlet:context-path: /app #设置应用名

这个设置后,URL要插入/app, 如http://localhost:8080/app/hello.html。


2.基本语法

表达式

表达式名字 语法 用途
变量取值 ${…} 获取请求域、session域、对象等值
选择变量 *{…} 获取上下文对象值
消息 #{…} 获取国际化等值
链接 @{…} 生成链接
片段表达式 ~{…} jsp:include 作用,引入公共页面片段

字面量

文本值: ‘one text’ , ‘Another one!’ ,…
数字: 0 , 34 , 3.0 , 12.3 ,…
布尔值: true , false
空值: null
变量: one,two,… 变量不能有空格

文本操作

字符串拼接: +
变量替换: |The name is ${name}|

数学运算

运算符: + , - , * , / , %

布尔运算

运算符: and , or
一元运算: ! , not

比较运算

比较: > , < , >= , <= ( gt , lt , ge , le )
等式: == , != ( eq , ne )

条件运算

If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)

特殊操作

无操作: _

3.设置属性值-th:attr

设置单个值

<form action="subscribe.html" th:attr="action=@{/subscribe}"><fieldset><input type="text" name="email" /><input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/></fieldset>
</form>

设置多个值

<img src="../../images/gtvglogo.png"  th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

官方文档 - 5 Setting Attribute Values

4.迭代

<tr th:each="prod : ${prods}"><td th:text="${prod.name}">Onions</td><td th:text="${prod.price}">2.41</td><td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'"><td th:text="${prod.name}">Onions</td><td th:text="${prod.price}">2.41</td><td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

5.条件运算

<a href="comments.html"th:href="@{/product/comments(prodId=${prod.id})}"th:if="${not #lists.isEmpty(prod.comments)}">view</a>
<div th:switch="${user.role}"><p th:case="'admin'">User is an administrator</p><p th:case="#{roles.manager}">User is a manager</p><p th:case="*">User is some other thing</p>
</div>

6.属性优先级

Order Feature Attributes
1 Fragment inclusion th:insert th:replace
2 Fragment iteration th:each
3 Conditional evaluation th:if th:unless th:switch th:case
4 Local variable definition th:object th:with
5 General attribute modification th:attr th:attrprepend th:attrappend
6 Specific attribute modification th:value th:href th:src …
7 Text (tag body modification) th:text th:utext
8 Fragment specification th:fragment
9 Fragment removal th:remove

官方文档 - 10 Attribute Precedence

web实验-后台管理系统基本功能

1.项目创建


选中以下场景
thymeleaf、
web-starter、
devtools、
lombok

2.登陆页面

/static 放置 css,js等静态资源

/templates/login.html 登录页

注意,要使用thymeleaf必须在文件头加上

thymeleaf超链接场景可以使用th:action替换action.另外,需要加上@{/…}

<html lang="en" xmlns:th="http://www.thymeleaf.org"><!-- 要加这玩意thymeleaf才能用 --><form class="form-signin" action="index.html" method="post" th:action="@{/login}">...<!-- 消息提醒 --><label style="color: red" th:text="${msg}"></label><input type="text" name="userName" class="form-control" placeholder="User ID" autofocus><input type="password" name="password" class="form-control" placeholder="Password"><button class="btn btn-lg btn-login btn-block" type="submit"><i class="fa fa-check"></i></button>...</form>

/templates/main.html 主页
取内容有以下两种写法:
以前

<p th:text ="#{home.welcome}">welcome to our group</p>

在标签的属性上写,内容会放在标签体里面。

thymeleaf内联写法:

<p>Hello, [[${session.user.name}]]!</p>
<img src="data:images/photos/user-avatar.png" alt="" />
[[${session.loginUser.userName}]]
<span class="caret"></span>

登录控制层

注意:这里有一个问题是表单的重复提交,也就是我们登陆之后,每次我们刷新表单,都是做了一次登陆的工作。由于我们是转发,所以我们每次提交,默认的还是提交login请求。如果我们是重定向到main页面,那么我们刷新是重定向到main页面。这里我们又要写一个main.html请求。以后我们一加html后缀,我们就知道这是跳转页面。不能直接/main.html来到main.html,templates文件夹下所有页面一定是通过请求处理,最后一定由模板引擎来解析的。直接访问是静态html。

@Controller
public class IndexController {//访问/或者/login都是来登录页./是根路径@GetMapping(value={"/","/login"})public String loginPage(){return "login";}/*return "main";这里每次刷新都都相当于做了一次重复提交,post请求无限提交上来,这里想相当于转发*/@PostMapping("/login")public String main(User user, HttpSession session, Model model){if(!StringUtils.isEmpty(user.getUserName()) && !StringUtils.isEmpty(user.getPassword())){//把登录成功的用户保存起来session.setAttribute("loginUser",user);//登录成功后重定向到main页面。//重定向防止表单重复提交。return "redirect:/main.html";}else{model.addAttribute("msg","账号密码错误");//回到登录页面return "login";}}//这里请求名是main.html,但是我们还是去main.html,之后每次刷新就是main.html@GetMapping("/main.html")public String mainPage(HttpSession session,Model model){//是否登录,拦截器,过滤器Object loginUser=session.getAttribute("loginUser");if(loginUser!=null){return "main";}else{//回到登录页面model.addAttribute("msg","请重新登录");return "login";}}
}

模型

@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {private String userName;private String password;
}

web实验-抽取公共页面

拷贝以下文件

注意,以上html文件都需要加上thymeleaf命名空间。

公共页面/templates/common.html

注意:

  1. <link href="css/style.css" th:href="@{/css/style.css}" rel="stylesheet">,使用th:href在加载的时候会自动加上项目名,比较方便。改变项目名无需修改源代码。<script th:src="@{/js/jquery.nicescroll.js}"></script>也是如此
  2. 不用th:fragment声明而用id声明,需要在引用的时候前面加上#
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><!--注意要添加xmlns:th才能添加thymeleaf的标签-->
<head th:fragment="commonheader"><!--common--><link href="css/style.css" th:href="@{/css/style.css}" rel="stylesheet"><link href="css/style-responsive.css" th:href="@{/css/style-responsive.css}" rel="stylesheet">...
</head>
<body>
<!-- left side start-->
<div id="leftmenu" class="left-side sticky-left-side">...<div class="left-side-inner">...<!--sidebar nav start--><ul class="nav nav-pills nav-stacked custom-nav"><li><a th:href="@{/main.html}"><i class="fa fa-home"></i> <span>Dashboard</span></a></li>...<li class="menu-list nav-active"><a href="#"><i class="fa fa-th-list"></i> <span>Data Tables</span></a><ul class="sub-menu-list"><li><a th:href="@{/basic_table}"> Basic Table</a></li><li><a th:href="@{/dynamic_table}"> Advanced Table</a></li><li><a th:href="@{/responsive_table}"> Responsive Table</a></li><li><a th:href="@{/editable_table}"> Edit Table</a></li></ul></li>...</ul><!--sidebar nav end--></div>
</div>
<!-- left side end--><!-- header section start-->
<div th:fragment="headermenu" class="header-section"><!--toggle button start--><a class="toggle-btn"><i class="fa fa-bars"></i></a><!--toggle button end-->...</div>
<!-- header section end--><div id="commonscript"><!-- Placed js at the end of the document so the pages load faster --><script th:src="@{/js/jquery-1.10.2.min.js}"></script><script th:src="@{/js/jquery-ui-1.9.2.custom.min.js}"></script><script th:src="@{/js/jquery-migrate-1.2.1.min.js}"></script><script th:src="@{/js/bootstrap.min.js}"></script><script th:src="@{/js/modernizr.min.js}"></script><script th:src="@{/js/jquery.nicescroll.js}"></script><!--common scripts for all pages--><script th:src="@{/js/scripts.js}"></script>
</div>
</body>
</html>

/templates/table/basic_table.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><meta name="description" content=""><meta name="author" content="ThemeBucket"><link rel="shortcut icon" href="#" type="image/png"><title>Basic Table</title><div th:include="common :: commonheader"> </div><!--将common.html的代码段 插进来-->
</head><body class="sticky-header"><section>
<div th:replace="common :: #leftmenu"></div><!-- main content start--><div class="main-content" ><div th:replace="common :: headermenu"></div>...</div><!-- main content end-->
</section><!-- Placed js at the end of the document so the pages load faster -->
<div th:replace="common :: #commonscript"></div></body>
</html>

Difference between th:insert and th:replace (and th:include)

区别
th:insert 如同插入的字面意思,将指定的代码片段插入主标签内
th:replace 如同替换的字面意思,将主标签替换为指定的代码片段
th:include (3.0版本后已不推荐使用) 类似于th:insert, 不同的是在插入的时候不带代码片段的标签,只插入代码
例子展示
被插入的代码

<footer th:fragment="copy">hello world
</footer>

三种方式使用

  <div th:insert="footer :: copy"></div><div th:replace="footer :: copy"></div><div th:include="footer :: copy"></div>

插入后的真实代码

 <div><footer>hello world</footer></div><footer>hello world</footer><div>hello world</div>

遍历数据与页面bug修改

注意在引用页面的时候一定要防止重复引用,否则会出现意向不到的错误。

控制层代码:

@GetMapping("/dynamic_table")
public String dynamic_table(Model model){//表格内容的遍历List<User> users = Arrays.asList(new User("zhangsan", "123456"),new User("lisi", "123444"),new User("haha", "aaaaa"),new User("hehe ", "aaddd"));model.addAttribute("users",users);return "table/dynamic_table";
}

页面代码:
这里可以通过stats加上遍历的状态。遍历的状态就会有索引、计数。状态以逗号分割,前面是当前元素,后面是当前元素的状态。

<table class="display table table-bordered" id="hidden-table-info"><thead><tr><th>#</th><th>用户名</th><th>密码</th></tr></thead><tbody><tr class="gradeX" th:each="user,stats:${users}"><td th:text="${stats.count}">Trident</td><td th:text="${user.userName}">Internet</td><td >[[${user.password}]]</td></tr></tbody>
</table>

Springboot视图解析与模板引擎相关推荐

  1. springboot视图解析器配置

    Springboot视图解析器配置 #spring.thymeleaf.cache = true #启用模板缓存. #spring.thymeleaf.check-template = true #在 ...

  2. 一头扎进springboot之使用Freemarker模板引擎渲染web视图

    在springboot的官方文档中是不建议在项目中使用jsp这样的技术的,取而代之的是freemark.velocity这样的模板引擎. 首先和大家来说一下这个模板引擎的概念,这里特指用于web开发的 ...

  3. SpringBoot-视图解析与模板引擎

    1.视图解析 视图解析:SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染. 1.1.视图解析原理流程 目标方法处理的过程中,所有数据都会被放在 ModelAndViewC ...

  4. 【SpringBoot】3、SpringBoot中整合Thymeleaf模板引擎

    SpringBoot 为我们提供了 Thymeleaf 自动化配置解决方案,所以我们在 SpringBoot 中使用 Thymeleaf 非常方便 一.简介 Thymeleaf是一个流行的模板引擎,该 ...

  5. springboot 整合 freemarker前端模板引擎实现数据展示

    一.freemaker 1.简介 FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页.电子邮件.配置文件.源代码等)的通用工具. 它不是面向最终用户 ...

  6. springboot视图解析器

    视图解析器:简单来说,将用户请求转到对应页面 方式一:application.properties #配置视图解析器 spring.mvc.view.prefix=/WEB-INF/pages/ sp ...

  7. springboot项目使用beetl模板引擎生成word文件

    一.详情可查看官网 1.官方网址:beetl官网 一.简单测试beetl生成word文件 1.在springboot项目中添加beetl的依赖 <dependency><groupI ...

  8. springboot 设置ico_Spring Boot--Thymeleaf模板引擎/静态页面

    点关注,不迷路:持续更新Java相关技术及资讯!!! 1.Spring Boot对静态资源的映射规则 如果静态资源文件夹下有 index.html的话,直接访问localhost:8080的话,ind ...

  9. SpringBoot (二) 整合前端模板引擎FreeMarker、thymeleaf

    哈喽,大家好,我是有勇气的牛排(全网同名)

最新文章

  1. paoding java_中文分词器-PaodingAnalyzer
  2. Ubuntu16.04如何彻底删除Apache2
  3. UI设计培训分享:ui设计师如何培养设计思维?
  4. iOS 排序算法总结、二分法查找
  5. Visual Studio 起始页中不显示最近使用的项目的解决办法
  6. 九个PHP很有用的功能
  7. OpenShift 4 - Fedora CoreOS (4) - 用 Ignition 定制 CoreOS 的网络/存储等配置
  8. 线程的生命周期图(附多线程)
  9. [转载] python模块的分类有哪些_整理了一份清单,常见Python问题的快速解答包
  10. 程序员最常见的技术性误区
  11. BGP超级失误:Verizon 搞垮 Cloudflare 和 AWS 等巨头,导致“连锁灾难性故障”
  12. mysql数据库学习——2,数据库的选定,创建,删除和变更
  13. JS 延时函数 setTimeout 或者 rxjs 写法
  14. 计算机小知识140,140个电脑小知识,电脑知识-
  15. 读书笔记 ---《偷影子的人》
  16. 平头哥RVB2601开发板开发环境CDK
  17. 数据挖掘概念与技术——读书笔记(1)
  18. STL queue:男孩被绑架了!
  19. 从源码编译usbmuxd
  20. Markdown博文快速转为微信文章

热门文章

  1. 拳王虚拟项目公社:如何如何打造虚拟自动盈利系统,用虚拟资源实现被动收入?
  2. 华为P30系列高清渲染图曝光:后置三摄拍照要上天
  3. udhcpc 后台运行的方法【总结】
  4. 分析rss/xml结构附带源码【原创】
  5. 无向简单图怎么判断_bfs----判断无向简单图中任意两点是否连通
  6. appcrash事件怎么解决_突发事件中身心容易紧张焦虑,该如何控制心理压力与情绪?...
  7. 关于socket组播和ssdp(二)
  8. c++自由读写配置ifstream(一)
  9. activitimq集群搭建_Spring-activiti
  10. 嵌入式Linux入门13:应用层调试