在 Spring Boot 应用程序中提供HTML、css、javascript等静态资源

x33g5p2x  于2022-10-06 转载在 Spring  
字(1.9k)|赞(0)|评价(0)|浏览(419)

本教程将教您如何配置 Spring Boot,以便在您的 Web 应用程序中提供静态资源(HTML、css、javascript)。

包含一个能够提供静态资源的依赖项

首先,确保您包含一个允许您使用 HTML 或静态资源的依赖项,例如 Thymeleaf:

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

静态资源位置

然后,您需要将静态文件放置在适当的位置。 Spring Boot 中可以放置静态文件的位置,从最高优先级到最低优先级是:

  • src/main/resources/resources
  • src/main/resources/static
  • src/main/resources/public

例如,请参阅以下 Web 应用程序的结构,它从三个不同的位置提供 index1.html、index2.html 和 index3.html:

src 
├── main 
│   ├── java 
│   │   └── com 
│   │       └── example 
│   │           └── SimpleMvcSpringBootApplication.java 
│   └── resources 
│       ├── application.properties 
│       ├── public 
│       │   └── index2.html 
│       ├── resources 
│       │   └── index3.html 
│       ├── static 
│       │   └── index1.html 
│       └── templates 
	└── test
		└── java         
			└── com             
				└── example                 
				└── SimpleMvcSpringBootApplicationTests.java

使用视图控制器将 URL 与资源进行映射

ViewControllerRegistry 注册一个视图控制器。当我们只需要使用 addViewController(String urlPath) 将 URL 映射到视图时使用它。这将为给定的 URL 添加一个视图控制器。例如,假设我想将 login.html 根到 /login,将 savepassword.html 根到 /savepassword,最后将 index.html 根到 /。这是如何做到的:

@Override
  public void addViewControllers(ViewControllerRegistry registry) {
    super.addViewControllers(registry);
    registry.addViewController("/savepassword").setViewName("savepassword.html");
    registry.addViewController("/login").setViewName("login.html");
    registry.addViewController("/").setViewName("loggedin/index.html");
  }

在 Spring Boot 中访问 Javascript 和 css

Css 和 javascript (.js) 文件是静态资源,Spring Boot 默认将其映射到 /resources/static 文件夹中。例如,在文件夹 src/main/resources/static/css 中定义一个文件 style.css 文件

h1 {   background-color: green;   color: red;   text-align: center; }

现在您可以按如下方式引用您的css:

<html>
	<head>
		<link href="css/style.css" rel="stylesheet">
	</head>
		<h1>Spring boot example</h1>
</html>

这是最终的项目结构:

├── src 
│   ├── main 
│   │   ├── java 
│   │   │   └── com 
│   │   │       └── example 
│   │   │           └── SimpleMvcSpringBootApplication.java 
│   │   └── resources 
│   │       ├── application.properties 
│   │       ├── static 
│   │       │   ├── css 
│   │       │   │   └── style.css 
│   │       │   └── index1.html 
│   │       └── templates

相关文章