Spring Boot web开发(静态资源、配置视图 jsp + thymeleaf )

1. 静态资源

web开发中的静态资源:图片,视频,css,html(不带引擎表达式),音频,js

src/main/resources是存放资源文件的目录(application.yml,或者其他目录static,templates)

src/main/resources/static是用于存放网页静态资源的目录,如css、js和图片等

springboot默认配置不仅仅只有static目录,还有以下几个目录

默认拦截路径为/**, 首页为在如下路径下查找:

"classpath:"代表就是src/main/resources

classpath:/META-INF/resources/

classpath:/resources/       相当于src/main/resources/resources

classpath:/static/                (一般用这个)

classpath:/public/

引入静态资源还可以通过webjar来引入(在WebMvcAutoConfiguration类中可以看到)

WebJars是将客户端(浏览器)资源(JavaScript,Css等)打成jar包文件,以对资源进行统一依赖管理。WebJars的jar包部署在Maven中央仓库上。

使用步骤:

(1)在https://www.webjars.org/找到对应资源的Webjar

(2)引入依赖

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.4.1-1</version>
</dependency>

(3)在HTML中使用

2. 配置视图

Spring Boot 默认模板引擎是 Thymeleaf

src/main/resources/templates,用于存放视图文件(例如jsp,thymeleaf的HTML文件)

【注意:放在里面的html或者jsp只能用控制器去访问

(1)添加依赖

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

(2)写一个api,将一个字符数据存到model里面返回到hello.html页面显示

@Controller
public class HelloController {

   
/**
     *
返回数据到页面
     * @return
    
*/
   
@RequestMapping("/hello")
   
public String hello (Model model){
        model.addAttribute(
"name","cjy");
       
return "hello";
    }
}

(3)在src/main/resources/templates目录下新增hello.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>欢迎</title>
</head>
<body>
    欢迎<strong th:text="${name}">匿名</strong>
</body>
</html>

(4)在浏览器中输入http://localhost:8080/hello 如下图效果

Spring Boot web开发(静态资源、配置视图 jsp + thymeleaf )

3. thymeleaf使用例子

实体类

Spring Boot web开发(静态资源、配置视图 jsp + thymeleaf )

Spring Boot web开发(静态资源、配置视图 jsp + thymeleaf )

Spring Boot web开发(静态资源、配置视图 jsp + thymeleaf )

相关文章: