SpringBoot配置静态文件跟原来的jsp略有不同啊,静态文件都放在了类路径的地址上,以前都是放到webapp下面,在配置文件中可以通过
spring.mvc.static-path-pattern
的方式来指定。第二种,是通过代码注册WebMvcConfigurerAdapter
,来配置静态文件。
配置文件配置的方式(推荐)
1、配置静态文件地址
#访问请求的前缀
spring.mvc.static-path-pattern: /static/**
#静态文件地址(系统路径),file:D:/static
#类路径的文件地址 (这个默认是类路径,所以一般不用设定)
spring.resources.static-locations=classpath:/static/
下面是完整配置
logging:
#日志存储地址
file: "logs/config/demo-xx.log"
info:
name : "入门案例"
server:
#端口号
#http://yellowcong.com:8888/
port: 8888
#项目名,如果不设定,默认是 /
context-path: /
---
#spring.mvc.resources
spring:
mvc:
#配置静态文件地址
static-path-pattern: /static/**
view:
# 页面默认前缀目录
prefix: /WEB-INF/jsp/
# 响应页面默认后缀
suffix: .jsp
2、配置静态文件
静态文件夹目录,在src/main/resources
目录下面。
3、访问服务
http://yellowcong.com:8888/static/js/jquery-1.7.1.js
代码指定的方式
启动类注册静态文件适配器
通过代码的这种方式,来搞起来比较麻烦,还不好找,所以一般建议使用使配置文件的方式
@Component
public class MyResHandler extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}
完整代码
package com.yellowcong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
public class ConfigMain {
/**
* @author yellowcong
* 创建日期:2018/02/05
* 设定首页
*/
@Configuration
public class DefaultView extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//设定首页为index
registry.addViewController("/").setViewName("forward:/index");
//设定匹配的优先级
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
//添加视图控制类
super.addViewControllers(registry);
}
}
@Component
public class MyResHandler extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}
public static void main(String[] args) {
SpringApplication.run(ConfigMain.class, args);
}
}