Thymeleaf模板引擎和Webjars联合使⽤

1.添加Thymeleaf依赖

<!--thymeleaf模板引擎依赖-->
<dependency>  
<groupId>org.springframework.boot</groupId>    
<artifactId>spring-boot-starter-thymeleaf</artifactId> 
</dependency

2.代码⽬录结构

8SU0PLPL$$EGX0P)QJS7K_0.png

resources下static⽂件夹存放images、css、js等静态资源
templates存放Thymeleaf模板⻚⾯

3.Controller层代码写法

package com.example.quickstart.controller;

import com.example.quickstart.entity.Student; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;

@Controller
public class IndexController {
//注入了一个Student类的对象,被Spring容器托管——bean
@Resource
private Student student;
//Get请求映射
@GetMapping("index")
  public String index(ModelMap map) {
    student.setName("Tom");
    student.setAge(20);
    student.setMale("男");
    //将模型加入视图
    map.addAttribute("student",student);
    return "index";
  }
}

4.html⻚⾯头部添加thymeleaf名称空间声明

<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>主页</title>
</head>
<body>
  <p th:text="${stduent.name}"></p>
</body>
</html

5.通过Webjars引⽤静态资源

Web前端使⽤了越来越多的JS或CSS,⼀般情况下,我们是将这些Web资源拷⻉到 Java的⽬录下,或者通过CDN引⽤,通过⼿⼯进⾏管理,这种⽅式容易导致⽂件混乱、 版本不⼀致等问题。 WebJars是将这些通⽤的Web前端资源打包成Java的Jar包,然后借助Maven⼯具对 其管理,保证这些Web资源版本唯⼀性,升级也⽐较容易。关于Webjars资源,有⼀个 专⻔的⽹站http://www.webjars.org/,我们可以到这个⽹站上找到⾃⼰需要的资源, 在⾃⼰的⼯程中添加⼊maven依赖,即可直接使⽤这些资源了。
如:⼀个使⽤bootstrap的Webjars的例⼦:

<dependency>
 <groupId>org.webjars</groupId>
 <artifactId>bootstrap</artifactId>
 <version>3.3.7-1</version>
</dependency>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="zh-CN">
<head>
 <meta charset="UTF-8"/>
 <title>欢迎页面</title>
 <link rel="stylesheet" 
 href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
<body>
 <div class="alert alert-success">
   <p th:text="${info}"></p>
</div>
</body>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容