-
[Spring] 정적 리소스 매핑Spring(스프링) 2020. 2. 12. 22:58반응형
스프링을 사용하여 웹 페이지를 만들었을 때, 파일 업로드 기능을 빼먹을 수 없다.
그중 사진을 업로드에 대한 기능을 제공한다면 정적 리소스 매핑 기능을 필요로 할 것이다.
WebMvcConfigurer 를 상속받아서 정적 파일에 대한 프로세스를 변경할 수 있다.
그렇다면 왜 이것을 사용해주어야 할까?
사실 이 기능을 사용하지 않아도 웹 페이지는 정상적으로 작동하며 파일이나 사진을 업로드하는 것도 가능하다.
하지만 업로드된 파일이 static 폴더에 업로드가 되어서 그 파일을 제대로 불러오기까지는 시간을 소요할 수 있다.
서버의 성능과 인터넷속도가 엄청 빠르다면 순식간에 모든 처리가 끝나서 정상적으로 웹페이지가 작동할 수 있을지는 알 수 없지만, 그런 고사양을 기대하는 것보다는 간단한 소스 처리로 문제를 해결할 수 있다.
클래스 상에서는 아래와 같은 코드를 통하여 정적리소스 매핑이 가능하다
package com.bitc502.grapemarket.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.resource.PathResourceResolver; @Configuration public class WebConfig implements WebMvcConfigurer { @Value("${file.path}") private String fileRealPath; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry.addResourceHandler("/upload/**").addResourceLocations("file:///" + fileRealPath).setCachePeriod(3600) .resourceChain(true).addResolver(new PathResourceResolver()); } }
class 대신 yml 파일을 설정하는것으로도 위의 기능을 대체할 수 있다.
spring: mvc: static-path-pattern: /static/**