Spring Boot 静态资源处理,妙!
阅读本文大概需要 4 分钟。
来自:cnblogs.com/paddix/p/8301331.html
一、最笨的方式
@Controller
public class StaticResourceController {
@RequestMapping("/static/**")
public void getHtml(HttpServletRequest request, HttpServletResponse response) {
String uri = request.getRequestURI();
String[] arr = uri.split("static/");
String resourceName = "index.html";
if (arr.length > 1) {
resourceName = arr[1];
}
String url = StaticResourceController.class.getResource("/").getPath() +
"html/" + resourceName;
try {
FileReader reader = new FileReader(new File(url));
BufferedReader br = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
response.getOutputStream().write(sb.toString().getBytes());
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、Spring boot默认静态资源访问方式
classpath:/public/ classpath:/resources/ classpath:/static/ classpath:/META-INFO/resouces/
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
http://localhost:8080/1.html http://localhost:8080/2.html http://localhost:8080/3.html http://localhost:8080/4.html
三、自定义静态资源目录
@Configuration
public class ImageMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/image/**")
.addResourceLocations("classpath:/images/");
}
}
spring:
mvc:
static-path-pattern: /image/**
resources:
static-locations: classpath:/images/
四、总结
classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
推荐阅读:
JVM 有 Full GC,为什么还会出现 OutOfMemoryError呢?
最近面试BAT,整理一份面试资料《Java面试BATJ通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
朕已阅