[Spring Boot #12] 스프링 웹 MVC - 정적 리소스
- 📚 Spring/Spring Boot
- 2020. 5. 3. 23:46
| 스프링 부트 정적 리소스 지원
스프링부트에서 정적리소스 지원할 때 URL의 root(/) 에 자동적으로 정적 리소스를 매핑할 수 있다.
resource/static/hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Hello static resource
</body>
</html>
http://localhost:8080/hello.html 로 연결 시 다음과 같이 브라우저에 출력 된다.
| application.properties를 통한 정적 리소스 매핑
application.properties에 아래내용으로 설정
spring.mvc.static-path-pattern=/static/**
http://localhost:8080/static/hello.html 로 static경로를 붙여 연결해야한다.
| WebMvcConfigurer를 통한 정적 리소스 매핑
스프링부트가 제공하는 기존의 ResourceHandler를 유지하면서 내가 원하는 리소스핸들러만 추가할 수 있다.
소스
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/m/**")
.addResourceLocations("classpath:/m/")
.setCachePeriod(20);
}
}
- addResourceHandlers는 리소스 등록 및 핸들러를 관리하는 객체인 ResourceHandlerRegistry를 통해 리소스 위치와 해당 리소스와 매칭될 URL을 등록한다
- setCachePeriod는 캐시가 얼마나 지속할 지 정하는 메서드이다. (나는 20초로 설정함)
static/m/hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Hello mmmm resource
</body>
</html>
http://localhost:8080/m/hello.html 로 요청하면 다음과 같이 출력된다.
| 스프링부트에서 jQuery 의존성 추가
Maven기반에서는 pom.xml에 아래의 jquery 의존성을 추가한다.
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1 </version>
</dependency>
또한 jQuery에서 자동 버전관리하기 위한 의존성 추가를 아래와 같이 할 수도 있다.
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
<version>0.35</version>
</dependency>
resources/m/hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Hello mmmm resource
<script src="/webjars/jquery/3.3.1/dist/jquery.min.js"></script>
<script>
$(function(){
alert("ready jquery!");
});
</script>
</body>
</html>
http://localhost:8080/m/hello.html로 접속하면 다음과 같이 브라우저에 출력된다.
'📚 Spring > Spring Boot' 카테고리의 다른 글
[Spring Boot #14] 스프링 웹 MVC - Thymeleaf (0) | 2020.05.04 |
---|---|
[Spring Boot #13] 스프링 웹 MVC - index페이지와 파비콘 (0) | 2020.05.04 |
[Spring Boot #11] 스프링 웹 MVC - HttpMessageConverters (0) | 2020.05.03 |
[Spring Boot #10] 스프링 부트 테스트 (Spring Boot Test) (0) | 2020.04.29 |
[Spring Boot #9] 스프링 부트 로깅(Logging) (0) | 2020.04.28 |