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.

  总结:通过上面的基本解释可以推导。在写网页时,不可能把数据写到模板中,而是应该在Controller中把数据送到模板中。

  Thymeleaf常用语法传送门

  注:<!DOCTYPE html>表示告诉浏览器文档使用html文档规范。

    lang="en" 表示当前显示为英文,也可以显示中文。谷歌浏览器会提示是否将页面翻译成英文。如果设置了自动翻译的话。

    

 

猜你喜欢

转载自www.cnblogs.com/yulianggo/p/10455754.html