关键就是启动类中registry的配置,也就是第二步
1.maven中加入依赖
<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>
</dependency>
<!--引入NekoHTML,配合spring.thymeleaf.mode=LEGACYHTML5使用,使Thymeleaf 可以解析非严格html格式的文档-->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
2.启动类配置:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@SpringBootApplication
public class DemoApplication extends WebMvcConfigurationSupport{
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
//这里配置静态资源文件的路径导包都是默认的直接导入就可以
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//因为有这一句,templates目录下的静态资源才能被加载,适用非标准目录
registry.addResourceHandler("/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/templates/");
//因为有这一句,static目录下的静态资源才能被加载,适用标准目录
registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/");
super.addResourceHandlers(registry);
}
}
整体目录:
标准目录:
静态资源放入static目录,html页面放入templates目录
非标准目录:
管他三七二十一
全放进templates
3.application.yml配置
server:
port: 8080
spring:
thymeleaf:
cache: false
encoding: UTF-8
mode: LEGACYHTML5
prefix: classpath:/templates/
suffix: .html
check-template-location: true
4.controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.HashMap;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String helloHtml(HashMap<String, Object> map) {
map.put("hello", "欢迎进入HTML页面");
return "/index";
}
@RequestMapping("/")
public String Html(HashMap<String, Object> map) {
map.put("hello", "欢迎进入HTML页面");
return "/index";
}
@RequestMapping("/login")
public String login(HashMap<String, Object> map) {
return "/login";
}
}
5.页面资源
<link rel="icon" href="img/core-img/favicon.ico">
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css">
源码:
点击跳转点击即可跳转至下载页面(附带精美前端音乐模板)