spring搭建网站后记之模板初探

  之前在Controller包中简单处理了URL的Path参数。包括PathVariable和RequestParam。

  但是网页是很复杂的,里面有很多图片,元素。如果将这些都写在Controller层,会使其过于庞大。因此,可以把这些网页的处理放到一个文件里面,然后在Controller里面返回这个文件,这个文件就叫模板。这样使得Controller文件很简洁。

@ResponseBody注解的作用

  之前的程序中,每次都在public返回函数前面加@ResponseBody,现在我注释掉这个注解。

  显示为:

    Error resolving template [Hello_World], template might not exist or might not be accessible by any of the configured Template Resolvers:意思是模板Hello_World不存在或者不能被访问。

  通过资料知道,@ResponseBody让返回结果直接写入Http正文中。不加@ResponseBody,return时,跳转到templates包下找return的指定的文件,返回文件的内容。参考资料传送门

   例子:

  1.在Controller包文件中,加入下列代码,表示当访问/hello路径时,返回Hello.html(.html可以省略)文件。

1     @RequestMapping(value = {"/hello"})
2     public String Hello_World() {
3         return "Hello";
4     }

  2.在Templates包下面创建Hello.html文件。Hello.html文件内容如下:

1 <html>
2 <head>
3     <title>Welcome!</title>
4 </head>
5 <body>
6     <h1>Welcome</h1>
7 </body>
8 </html>

  显示结果:

    

Thymeleaf

  什么是Thymeleaf?

  Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.

  Tymeleaf具体干了什么?

  It builds on the concept of Natural Templates to inject its logic into template files in a way that doesn’t affect the template from being used as a design prototype.

  Thymeleaf能处理哪些模板模式?

  Out-of-the-box, Thymeleaf allows you to process six kinds of templates, each of which is called a Template Mode:HTML,XML,TEXT,JAVASCRIPT,CSS,RAW.

  总结:通过上面的基本解释可以推导。前端语言跟模板语言完全就是不同的概念。HTML有自己的语法,而Thymeleaf有自己的语法。例如:

  HTML注释用<!-- -->

  Thymeleaf中用<!--/*--> <!--*/-->

  模板语言在这里的作用就是,将Controller的数据写道HTML文件中。

  Thymeleaf常用语法传送门

Thumeleaf实验

  1.Controller部分定义一个aaa变量,值为"naive"。

1     @RequestMapping(path = {"/hello"})
2     public String Hello_World(Model model) {
3         model.addAttribute("aaa", "naive");
4         return "Hello";
5     }

  2.模板部分使用aaa变量:

1 <html>
2 <head>
3     <title>Welcome!</title>
4 </head>
5 <body>
6     <h1>Welcome</h1>
7     <p th:text="${aaa}" />
8 </body>
9 </html>

  输出结果:

 

 个人感觉这个模板语言有点冗余,<p th:text="${aaa}" />这么多代码才能显示一个变量。期待打脸。

  

原文地址:https://www.cnblogs.com/yulianggo/p/10455754.html