1. springboot項目訪問html頁面
記錄一下在springboot項目中如何訪問html頁面的配置,免得每次需要的時候又得到處去找,找了又忘
2. 創建一個基於springboot框架的web應用,不需要其它依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>qinfeng.zheng</groupId>
<artifactId>springboot-iview</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-iview</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3. application.properties配置
# 配置靜態資源地址,默認地址:"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/
spring.resources.static-locations=classpath:/templates/
# 如果將html頁面直接放在templates目錄下,可能省略下面這行配置
spring.mvc.view.prefix=views
# 必須的,不然報錯
spring.mvc.view.suffix=.html
server.port=8089
4. 配置文件
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Author ZhengQinfeng
* @Date 2020/11/12 22:04
* @dec
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// spring.mvc.view.prefix + /index + spring.mvc.view.suffix 構成完整的請求地址
// 訪問項目根目錄即是訪問 /views/index.html頁面
registry.addViewController("/").setViewName("/index");
}
}