spring boot静态资源的目录结构如下:
spring-boot项目静态文件目录:/src/main/resources/static
spring-boot项目模板文件目录:/src/java/resources/templates
spring-boot建议不要使用JSP,默认使用Thymeleaf来做动态页面。
在pom.xml 中添加Thymeleaf组件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Spring-boot使用thymeleaf时默认是有缓存的,即你把一个页面代码改了不会刷新页面的效果,你必须重新运行spring-boot的main()方法才能看到页面更改的效果。我们可以把thymeleaf的缓存关掉,用于支持页面修改后重新发布到spring-boot内嵌的tomcat中去。在application.properties配置文件中加入以下配置。
spring.thymeleaf.cache: false
server.tomcat.access_log_enabled: true
server.tomcat.basedir: target/tomcat
使用普通注解@Controller 返回页面
@Controller
public class TemplatesController {
@GetMapping("/index")
String test(HttpServletRequest request) {
return "index";
}
}
spring boot结合vue框架的话需要修改静态文件的配置路径,解决方法有两种:
方法一、
修改application.properties配置文件,加入以下配置:
spring.mvc.static-path-pattern =/static/**
则访问静态文件的路径为:
http://localhost:8080/static/tinymce/tinymce.min.js
方法二、
通常情况下,Spring Boot的自动配置是符合我们大多数需求的。在你既需要保留Spring Boot提供的便利,有需要增加自己的额外的配置的时候,可以定义一个配置类并继承WebMvcConfigurerAdapter,无需使用@EnableWebMvc注解。
这里我们提到这个WebMvcConfigurerAdapter这个类,重写这个类中的方法可以让我们增加额外的配置,这里我们就介绍几个常用的。
自定义资源映射addResourceHandlers
比如,我们想自定义静态资源映射目录的话,只需重写addResourceHandlers方法即可。
通过addResourceHandler添加映射路径,然后通过addResourceLocations来指定路径。我们访问自定义my文件夹中的elephant.jpg 图片的地址为http://localhost:8080/my/elephant.jpg