SpringBoot Web开发基础 模板引擎Thymeleaf

1、Web开发步骤

(1)创建SpringBoot应用,勾选需要的模块(各个子框架)

(2)SpringBoot会自动配置好相关模块的场景(所有配置都在自动配置包下),我们只需要在配置文件中指定少量配置

(3)自己编写业务代码

2、静态资源映射 https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-spring-mvc-static-content

/**的意思是所有文件夹及里面的子文件夹

/*是所有文件夹,不含子文件夹

2.1 导入外部前端框架(以导入jquery为例,非常方便)

放置目录:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-spring-mvc-static-content

webjars:以jar包的形式引入静态资源  比如引入jQuery,就可以直接下载jquery.jar来用了。

https://www.webjars.org/ 可以直接搜索想要的jar包,复制坐标,交给maven部署就是了。

这个方法下载的jar包,会被SpringBoot自动放置在SpringBoot要求的目录下(即自动对应SpringBoot资源映射)

2.2 导入自己的静态资源

SpringBoot能寻找这些资源的位置

"classpath:/META-INF/resources/"

"classpath:/resources/"

"classpath:/static/"

"classpath:/public"

"/":当前项目的根路径

2.3 欢迎页面 index.html   https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-spring-mvc-static-content

    将index.html文件夹 随意放在上面的静态目录里,就会被检索到

2.4 配置网页标签图标

    将喜欢的网页标签的.ico图片,放在上面的静态目录里就好。

2.5 修改默认静态文件夹 https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-spring-mvc-auto-configuration

     By default, resources are mapped on /**, but you can tune that with the spring.mvc.static-path-pattern property. For instance, relocating all resources to /resources/** can be achieved as follows:

//spring.mvc.static-path-pattern=/resources/**

3、模板引擎 https://docs.spring.io/spring-boot/docs/2.4.1/reference/htmlsingle/#boot-features-spring-mvc-template-engines

模板引擎有很多,比如JSP、velocity、Freemarker、Thymeleaf(SpringBoot用的这个)

3.1 Thymeleaf引擎介绍https://www.thymeleaf.org/

Thymeleaf特色:语法更简单,功能更强大

(1)在SpringBoot中引入Thymeleaf

     通过SpringBoot starter启动,https://docs.spring.io/spring-boot/docs/2.4.1/reference/htmlsingle/#using-boot-starter

可以看到spring-boot-starter-thymeleaf

然后通过maven在pom.xml文件中 输入依赖,就会引入

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf<artifactId>  //直接粘贴starter里面的spring-boot-starter-thymeleaf,就会自动识别剩下的

</dependency>

(2)SpringBoot中启用Thymeleaf

https://docs.spring.io/spring-boot/docs/2.4.1/reference/htmlsingle/#boot-features-webflux-template-engines

当你将html文件放到src/main/resources/templates目录下,模板引擎就能自动渲染啦

When you use one of these templating engines with the default configuration, your templates are picked up automatically from src/main/resources/templates.

exp: success.html文件必须在src/main/resources/templates 目录下, SpringBoot才找得到

src/java/.../controller  目录下

@Controller
public class HelloController{
  @RequetMapping("/success") //对浏览器的/success请求响应
  publicMappiing("/success") //响应一个success.html文件
}

特别注意:根据官方文档3.1,前端html中,需要先导入Thymeleaf命名空间(直接复制过来),这样才会有语法提示

<html lang="en" xmlns:th="http://www.thymeleaf.org">

3.2 Thymeleaf语法 

(1)th:xx   改变html标签的任意属性值

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#attribute-precedence

官方教学文档第10节,Thymeleaf属性用法解释

<div id="div01" class="mDiv" th:id="cc" th:class="ss" th:text="${hello}">你好</div>

上例:div标签的 id属性被改成cc。class属性被改成ss。文本属性 你好 被改成 服务端键(key)hello对应的值

(2)表达式

    官方文档第四节https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax

Ⅰ 基本表达式(表达式语法)

Variable Expressions: ${...} //通过变量名获取属性值,通过对象调用方法  官方文档4.2

调用属性

<p>Today is: <span th:text="${today}">13 february 2011</span>.</p>

调用方法

<p th:utext="#{home.welcome(${session.user.name})}">
  Welcome to our grocery store, Sebastian Pepper!
</p>

 调用thymeleaf内置基本对象   https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-basic-objects

  • #ctx: the context object.
  • #vars: the context variables.
  • #locale: the context locale.
  • #request: (only in Web Contexts) the HttpServletRequest object.
  • #response: (only in Web Contexts) the HttpServletResponse object.
  • #session: (only in Web Contexts) the HttpSession object.
  • #servletContext: (only in Web Contexts) the ServletContext object.

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects  

Established locale country: <span th:text="${#locale.country}">US</span>.

调用thymeleaf内置工具对象 https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-utility-objects

  • #execInfo: information about the template being processed.
  • #messages: methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
  • #uris: methods for escaping parts of URLs/URIs
  • #conversions: methods for executing the configured conversion service (if any).
  • #dates: methods for java.util.Date objects: formatting, component extraction, etc.
  • #calendars: analogous to #dates, but for java.util.Calendar objects.
  • #numbers: methods for formatting numeric objects.
  • #strings: methods for String objects: contains, startsWith, prepending/appending, etc.
  • #objects: methods for objects in general.
  • #bools: methods for boolean evaluation.
  • #arrays: methods for arrays.
  • #lists: methods for lists.
  • #sets: methods for sets.
  • #maps: methods for maps.
  • #aggregates: methods for creating aggregates on arrays or collections.
  • #ids: methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

使用方法:参考https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects

Ⅱ Selection Variable Expressions: *{...} //选择表达式 参考官方文档4.3https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expressions-on-selections-asterisk-syntax

简介:*{...}表达式和${...}表达式在只有一个对象的时候,功能一样。

    在有多个对象时,*{...}表达式  搭配 th:Object ="{某对象}" 一起使用,实现选择对象

  <div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
    <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
  </div>

    相当于

<div>
  <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

Ⅲ  Message Expressions: #{...}

  获取国际化内容,参考官方文档4.1 https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#messages

Ⅳ Link URL Expressions: @{...}  

定义URL链接,参考官方文档4.4 https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#link-urls

 用@{...} 的好处是,链接里面的变量,可以很方便的更换。

<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" 
   th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>

<!-- 支持相对路径写法 -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

 

Ⅴ Fragment Expressions: ~{...

片段引用表达式,插入一个片段文档 参考官方文档4.5 https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#fragments

(3)Literals(字面量)

Text literals: 'one text''Another one!',…

Number literals: 0343.012.3,…

Boolean literals: truefalse

Null literal: null

Literal tokens: onesometextmain,…

(4)Text operations:文本操作

String concatenation: +

Literal substitutions: |The name is ${name}|

(5)Arithmetic operations:(基本数学运算)

Binary operators: +-*/%

Minus sign (unary operator): -

(6)Boolean operations: 布尔运算 

Binary operators: andor

Boolean negation (unary operator): !not

(7)Comparisons and equality: (比较运算,逻辑运算)

Comparators: ><>=<= (gtltgele)

Equality operators: ==!= (eqne)

(8)Conditional operators:  条件运算

If-then: (if) ? (then)

If-then-else: (if) ? (then) : (else)

Default: (value) ?: (defaultvalue)

Special tokens:  特殊操作

No-Operation: _

3.3 exp:查出用户数据,在页面展示

//服务端
@Controller
public class HelloController{
  @RequestMapping("/success")//响应前端的/success
  public String success(){
    map.put("hello","<h1>你好</h1>"); //模板引擎将会找键 hello的值
    map.put("users",Arrays.asList("zouzou","taotao","xiuxiu"));
    return "success"; //返回success.html网页
  }
}

 

扩展:遍历数组(对象属性) 官方文档第六章https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#using-theach

th:each=自定义变量名 : 服务端要遍历的对象名

th:each 每次都会取出服务端想遍历对象的一个值,赋给自定义变量名。

扩展:行内写法,官方文档12章 https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#inlining

如果觉得把修改的文本内容写在标签里 th:text 不舒服,可以用行内写法替代

Expressions between [[...]] or [(...)] are considered inlined expressions in Thymeleaf, and inside them we can use any kind of expression that would also be valid in a th:text or th:utext attribute.

<!--我很不爽会被你好替换 -->
<div id="div01" class="myDiv" th:class="${hello} th:text="${hello}">我很不爽</div>
<hr/>
<!--th:each每次遍历都会生成th:each所在的标签一次,3个span-->
<h4>
    <span th:each="user:${users}">[[${user}]]</span>
</h4>
<!--用了行内写法-->

4、SpringMVC自动配置  

参考官网:https://docs.spring.io/spring-boot/docs/2.4.1/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration

SpringBoot自动配置好了SpringMVC。但SpringBoot会先看容器中有没有用户自己配置的(@Bean、@Component),如果有,就用用户配置,,如果没有,才自动配置。如果有些组件可以有多个配置(比如视图解析器ViewResolver),SpringBoot会将用户配置的和自己默认的组合起来一起用。

 

 

 

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值