<Spring Boot> Static Resource Handle

Google 아니고 Joogle·2022년 6월 30일
0

Spring / Spring Boot 

목록 보기
2/5

https://github.com/JuyoungKimmy-Kim/spring-staticHandle.git

1. Static Resource?

html, css, image, javascript와 같이 컴파일이 필요 없는 파일

e.g. NAVER의 logo 검색 버튼 등은 홈페이지 개편등의 작업이 없는 한 거의 변하지 않는 정적자원(그 중 이미지)

스프링 부트에서 Web MVC 설정을 담당하는 WebMvcAutoConfiguration 클래스는 기본 설정으로 웹리소스 폴더에서 정적 자원들을 찾음

2. Image URL

  1. Resource 폴더 하위에 Static 폴더를 만들고 Static 폴더 하위에 images 폴더를 만들고 이미지 추가

  2. /src/main/resources는 클래스패스와 같고 static 폴더는 WebMvc AutoConfiguration 클래스에서 인식하므로 브라우저에서는 추가한 images 경로만 있으면 됨
    localhost:8080/images/이미지파일명 으로 접근 가능

3. HTML URL

  1. /src/main/resources/static/hello.html 파일을 새로 만듦

  2. localhost:8080/hello.html로 접근 가능

4. Static Resource 매핑 패턴 변경

정적 리소스 매핑 패턴을 루트가 아닌 다른 패턴으로 변경

application.properties - spring.mvc.static-path-pattern


5. Static Resource Location 변경

정적 리소스 location을 /static-test/로 변경

  1. src/main/resourcesstatic-test 디렉토리를 생성하고 hello.html위치

  2. application.properties - spring.resources.static-locations

  3. localhost://8080/hello.html 로 요청

6. Static Resource Handler Customizing

WebMvcConfigurer를 구현하는 클래스에서 addResourceHandlersoverride하여 정적 리소스 핸들러 커스터마이징 가능

  1. config package 생성 후 WebConfig class를 만듦

  1. /m/** 패턴 요청 시 classpath의 /m/ 디렉토리에서 정적 리소스를 찾아 응답하도록 하는 설정
    setCachePeriod를 통해 캐싱 전략을 설정

  2. src/main/resources에 m디렉토리를 만들고 hello.html위치

Reference
https://atoz-develop.tistory.com/entry/spring-boot-web-mvc-static-resources
https://jongminlee0.github.io/2020/03/13/resource/
스프링 부트로 배우는 자바 웹 개발 p94-99

profile
Backend 개발자 지망생

0개의 댓글