SpringBoot中web模板渲染怎么实现

发布时间:2022-02-08 16:31:29 作者:iii
来源:亿速云 阅读:167

这篇“SpringBoot中web模板渲染怎么实现”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“SpringBoot中web模板渲染怎么实现”文章吧。

模板

开发Web站点的本质,其实就是根据浏览器发起的请求(输入),生成HTML代码返回给浏览器(输出)。在之前的学习中,我们已经通过文件的形式存储起来而不是直接在Java代码中生成HTML代码。另一方面,博客站点是动态的,即不同的请求返回的内容可能不同。但是对于同一类请求,例如访问id分别为1和2的两篇文章,对应的URL分别为/blogs/1和/blogs/2,他们返回的HTML代码片段的结构几乎是一样的:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<div class="col-sm-8">
  <div class="page-header">
    <h3 th:text="${title}">Cum sociis(博客标题)</h3>
    <p class="blog-post-meta"><span th:text="${createdTime}">2015年2月3日</span> 标签:<a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >Web开发</a></p>
  </div>

  <div class="blog-post-content" th:text="${content}">
    ...
    (这里是博客内容)
  </div>
</div>
</html>

th:text="${title}"就是告诉模板引擎,用title变量作为<h3>标签的内容(createdTime,content也是一样)。

注意为了显示博客创建时间,我们将时间放入了一个<span>标签中,用于和其他文字区分开。

Model

为了让模板引擎知道这些变量的值,我们需要再@Controller做一些工作:

@RequestMapping("/index/{id}")
    public String getIndex(@PathVariable("id") int id ,Model model) {
//        return "index";
        //这里模拟一些数据
        model.addAttribute("title","This is a blog with id = " + id);
        model.addAttribute("CreatedTime","2017-11-13");
        model.addAttribute("content","This is content");
        return "index";
    }

在上面的代码中,index()方法增加了一个Model类型的参数。通过Spring MVC框架提供的Model,可以调用其addAttribute方法,这样Thymeleaf可以访问Model中的变量从而进行模板渲染。上述例子中可以看到,title变量的值是根据URL中的@PathVariable来确定的,虽然简单,但是这已经是一个动态页面了。

在Servlet编程中,如果希望在页面中动态渲染信息,一般需要往HTTPRequest中添加属性,然后再JSP中获取。其实Model的属性实际上也是放在HttpRequest的属性中,但是Spring MVC提供了更高层的抽象,帮你屏蔽了HttpRequest,你看到的只有直接以MVC中M(即Model)

如果你依然希望使用HttpRequest,HttpResponse和HttpSession等原生的Servlet API对象,往Controller方法中增加对应类型的参数即可,你在方法中就能直接使用了,Spring MVC会传递给你正确的对象。

运行结果:

SpringBoot中web模板渲染怎么实现

Model中添加对象

在上面的例子中,我们已经将单篇文章的页面动态化,但是这个动态化只是一个例子,当我们真正拥有数百篇博文时,并且还会添加(或者删除,更新)。显然不能够直接在@Controller方法中这样来填充Model,另外如果需要渲染文章列表,那么这种方法显然也是不行的。

为了解决这个问题,我们需要使用参考代码JAR包中提供的Blog类:

package Entity;

import java.util.Date;

public class Blog {
    private int id;
    private String title;
    private String content;
    private Date createdTime;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Date getCreatedTime() {
        return createdTime;
    }
    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }
    
}

在单篇文章页面里,对于每一个属性,都需要调用一次Model.addAttribute()方法,属性如果很多就会很不方便。现在我们有了Blog对象,可以将它放入Model:

@RequestMapping("/index/{id}")
    public String getIndex(@PathVariable("id") int id ,Model model) {
//        return "index";
        //这里模拟一些数据
//        model.addAttribute("title","This is a blog with id = " + id);
//        model.addAttribute("CreatedTime","2017-11-13");
//        model.addAttribute("content","This is content");
        Blog blog = new Blog();
        blog.setId(1);
        blog.setTitle("This is a blog with id = " + id);
        blog.setContent("This is content");
        blog.setCreatedTime(new Date());
        model.addAttribute("blog",blog);
        return "index";
    }

根据URL中的id获取对应的Blog对象,然后交给模板引擎渲染blog,相应的在模板中的变量表达式也要发生变化:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<div class="col-sm-8">
  <div class="page-header">
    <h3 th:text="${blog.title}">Cum sociis(博客标题)</h3>
    <p class="blog-post-meta"><span th:text="${blog.createdTime}">2015年2月3日</span> 标签:<a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >Web开发</a></p>
  </div>

  <div class="blog-post-content" th:text="${blog.content}">
    ...
    (这里是博客内容)
  </div>
</div>
</html>

运行结果:

SpringBoot中web模板渲染怎么实现

提高:往Model中添加对象有两种方式:

  1. model.addAttribute("blog",blog);

  2. model.addAttribute(blog);

使用第二种时,对象在Model中的命名默认为类名的首字母小写形式,任何时候对于同一种类型,只可能存在一个这样的“匿名”对象。

日期格式化

文章页面经过模板渲染处理后,还存在一个小问题:日期格式。现在对于${blog.createdTime}的渲染结果是Mon Nov 13 16:18:08 GMT+08:00 2017 ,这是因为${blog.createdTime}是一个Date对象,模板引擎在渲染的时候直接调用它的toString()方法。格式化日期是一个非常常见的任务,为此Thymeleaf提供了内置的支持:

<p><span th:text="${#dates.format(blog.createdTime,'yyy-MM-dd')}">2015年2月3日</span> 标签:<a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >Web开发</a></p>

#dates是Thymeleaf内置的一个工具类,format()方法可以指定日期的格式。

运行结果:

SpringBoot中web模板渲染怎么实现

以上就是关于“SpringBoot中web模板渲染怎么实现”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

推荐阅读:
  1. springBoot(6):web开发-模板引擎jsp
  2. springBoot(5):web开发-模板引擎FreeMarker与thymeleaf

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

springboot web

上一篇:Spring为什么需要三级缓存解决循环依赖

下一篇:C++的封装方法是什么

相关阅读

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

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