温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springBoot(5):web开发-模板引擎FreeMarker与thymeleaf

发布时间:2020-07-29 12:32:20 来源:网络 阅读:2488 作者:我爱大金子 栏目:开发技术

一、简介

spring boot的web应用开发,是基于spring mvc。


Spring boot在spring默认基础上,自动配置添加了以下特性:

 1、包含了ContentNegotiatingViewResolver和BeanNameViewResolver beans。

 2、对静态资源的支持,包括对WebJars的支持。

 3、自动注册Converter,GenericConverter,Formatter beans。

 4、对HttpMessageConverters的支持。

 5、自动注册MessageCodeResolver。

 6、对静态index.html的支持。

 7、对自定义Favicon的支持。

 8、主动使用ConfigurableWebBindingInitializer bean


二、模板引擎的选择

FreeMarker

Thymeleaf

Velocity (1.4版本之后弃用,Spring Framework 4.3版本之后弃用)

Groovy

Mustache

注:jsp应该尽量避免使用,原因如下:

 1、jsp只能打包为:war格式,不支持jar格式,只能在标准的容器里面跑(tomcat,jetty都可以)

 2、内嵌的Jetty目前不支持JSPs

 3、Undertow不支持jsps

 4、jsp自定义错误页面不能覆盖spring boot 默认的错误页面

三、FreeMarker使用

新建一个工程,勾选Freemarker、DevTools(开发方便)

springBoot(5):web开发-模板引擎FreeMarker与thymeleaf

会自动在pom.xml中加入Freemarker的配置:

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


WebController.java:

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by DELL on 2017/6/13.
 */
@Controller
@RequestMapping("/web")
public class WebController {
    private static final Logger logger = LoggerFactory.getLogger(WebController.class);

    @RequestMapping("/index")
    public String index(Model model){
        logger.info("这是一个controller");
        model.addAttribute("title","我是一个例子");
        return "index";  // 注意,不要再最前面加上/,linux下面会出错
    }
}

index.ftl:

<!DOCTYPE html>
<html>
<head lang="en">
   <title>Spring Boot Demo - FreeMarker</title>
    <link href="/css/index.css" rel="stylesheet" />
</head>
<body>
    <center>
        <img src="/images/logo.png" />
        <h2 id="title">${title}</h2>
    </center>

    <script type="text/javascript" src="/js/jquery.min.js"></script>

    <script>
        $(function(){
            $('#title').click(function(){
                alert('点击了');
            });
        })
    </script>
</body>
</html>


说明:

 1、视图默认访问templates下面,如"index",则:在templates下面找index.ftl

 2、css、js、img等静态资源则在static下面找,如<link href="/css/index.css" rel="stylesheet" />,则是找static下面的css下面的index.css文件

四、thymeleaf模块

4.1、简介

Thymeleaf是一个优秀的面向java的XML/XHTML/HTML5页面模板,并且有丰富的标签语言和函数。使用Springboot框架进行界面设计,一般都会选择Thymeleaf模板。

4.2、使用

引入依赖:

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


配置application.properties文件:

#####################thymeleaf开始#####################################
#关闭缓存
spring.thymeleaf.cache=false
#后缀
spring.thymeleaf.suffix=.html
#编码
spring.thymeleaf.encoding=UTF-8
#####################thymeleaf结束#####################################

IndexController.java:

@Controller
public class IndexController {
    @RequestMapping("/index")
    public String show(Model model) throws Exception {
        List<User> users = new ArrayList<User>();
        users.add(new User(1L, "zhangsan"));
        users.add(new User(2L, "lisi"));
        users.add(new User(3L, "wangwu"));
        model.addAttribute("hello","我只是一个例子");
        model.addAttribute("users", users);
        model.addAttribute("addtime",new Date());
        return"/helloHtml";
    }
}

main/resources/templates/helloHtml.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello World!</title>
</head><p th:text="${hello}"></p>
<body>
<h2 th:inline="text">Hello.v.2</h2>
<p th:text="${addtime} ? ${#dates.format(addtime, 'yyyy-MM-dd HH:mm:ss')}"></p>
<select>
    <option>请选择用户</option>
    <option th:each="user:${users}" th:value="${user.id}" th:text="${user.name}">
    </option>
</select>
</body>
</html>

浏览器中输入:http://localhost:8989/index ,效果如下:

springBoot(5):web开发-模板引擎FreeMarker与thymeleaf

4.3、thymeleaf功能简介

在html页面中使用thymeleaf标签语言,用一个简单的关键字“th”来标注,如:

<p th:text="${hello}"></p>
<img th:src="@{images/logo.png}" />

其中th:text指定在<p>标签中显示的文本,它的值来自"$"所引用的内存变量。

th:src指定img的图片地址


注意:使用th,需要<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

 springBoot(5):web开发-模板引擎FreeMarker与thymeleaf


thymeleaf的主要标签和函数:

th:text,显示文本。
th:utext,和th:text的区别是针对"unescaped text"。
th:attr,设置标签属性
th:if or th:unless,条件判断语句
th:switch, th:case,选择语句
th:each,循环语句

#date:日期函数
#calendars:日历函数
#numbers:数字函数
#strings:字符串函数
#objects:对象函数
#bools:逻辑函数
#arrays:数组函数
#lists:列表函数

详细标签请查看官方:http://www.thymeleaf.org/  


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI