一目录结构
二.springboot静态资源映射规则
-
对那些目录支持映射:
WebMvcAutoConfiguration类自动为我们注册了如下目录为静态资源目录,也就是说直接可访问到资源的目录。
classpath:/META-INF/resources/ classpath:/resources/ classpath:/static/ classpath:/public/ /:当前项目的根路径 简单来说: 就我们在上面五个目录下放静态资源(比如:a.js等),可以直接访问([http://localhost:8080/a.js](http://localhost:8080/app.js)),类似于以前web项目的webapp下;放到其他目录下无法被访问。
-
优先级:
优先级从上到下。
所以,如果static里面有个index.html,public下面也有个index.html,则优先会加载static下面的index.html,因为优先级!
三.静态资源请求:
springboot的请求路径一般会经过Controller处理,但是静态资源文件在请求之后是直接返回的。这涉及到俩个配置项,如果项目中没有设置,默认会执行这种配置
spring.mvc.static-path-pattern=/** 指的是请求路径。
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
指的是,静态资源目录,目录按配置顺序由先到后,优先级由高到低。
如果配置文件中配置为
spring.mvc.static-path-pattern:/static/**,
spring.resources.static-locations:classpath:/static/,classpath:/public/
即http://localhost:8088/static/index.html的请求会是一个静态请求;而http://localhost:8088/index.html的请求不是一个静态请求。
项目中的配置方式是:
package com.tsinkai.ettp.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
}
-
html中的引用方式
正确写法:<script src="/static/layui/layui.js">
错误写法:<script src="static/layui/layui.js"> controller写法
/**
* 配置jsp页面不能使用@RestController
*/
@Controller
//@ResponseBody
@RequestMapping("/dome")
public class DomeController {
@RequestMapping("/dome")
public String dome(){
System.out.println("---------");
return "index";
}
}