一.静态资源目录
默认静态资源目录为resources目录下的static
META-INF/resources、public、resources、static均为官方指定的静态资源目录,但除static外均需要自行创建
源码
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
读取优先级与源码中的排序相同
/META-INF/resources > resources > static > public
若不想使用官方指定的静态资源目录,可自行配置,但需要注意的是,一旦自行配置静态资源目录,官方配置将失效
spring.resources.static-locations=classpath:/目录1/,classpath:/目录2/ 优先级依排序而定
二.访问静态资源
1.在静态资源目录下添加index.html
2.访问
(1)可通过url直接访问
(2)可通过Controller层跳转
//此处需要返回html页面 故使用@Controller注解
@Controller
public class IndexController {
@RequestMapping("/index")
public String index(){
return "index.html";//访问静态资源记得带上后缀
}
}
关于注解,值得注意的是:
只使用 @RestController注解 则类无法返回jsp或者html 因为配置的视图解析器 InternalResourceViewResolver不起作用 返回的内容就是Return里的内容 若需要返回到指定页面 则需要使用 @Controller注解 配合视图解析器 InternalResourceViewResolver 若在此基础上需要返回JSON,XML或自定义的mediaType内容到页面 则需要在对应的方法上添加 @ResponseBody注解 @RestController注解 实质上是@Controller注解与@ResponseBody注解的合成注解 此处需要返回html页面 故使用@Controller注解 否则将返回"index.html" 字面意思
且访问静态资源记得带上后缀(index.html),区别于动态资源(无需后缀)
彩蛋-修改网页图标
将图片命名为favicon.ico,放入静态资源目录下
运行效果