Engineering Note

[Spring] 스프링에서 정적파일 처리하기 본문

Server/Spring

[Spring] 스프링에서 정적파일 처리하기

Software Engineer Kim 2025. 12. 30. 08:58

 

문제 상황

스프링 환경을 세팅하고 테스트를 위해 sample.htlm 정적파일(파일경로:resources/static/sample.html)을 브라우저에서 요청했을 때 에러가 발생했다.

 

 

에러 원인

Thymeleaf가 없는 환경에서 스프링 MVC의 모든 경로를 스프링에서 처리하려고 시도하기 때문

 

해결방법

리소스 핸들러로 경로를 지정해주면 된다.

package org.zerock.api01.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class CustomServletConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry){
    registry.addResourceHandler("/**")
        .addResourceLocations("classpath:/static/");
  }
}

 

"domain"에서 "/"(루트)경로 이하로 요는 URL요청은 classpath:/static/ 경로의 파일로 처리한다는 뜻이다. 기본 루트경로 하위는 컨트롤러나 타임리프 파일을 처리하기 위해, "/files" 이하로 수정해주었다.

 

package org.zerock.api01.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class CustomServletConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry){
    registry.addResourceHandler("/files/**")
        .addResourceLocations("classpath:/static/");
  }
}

 

 

참고자료: 자바웹개발 워크북(구멍가게 코딩단, p777)

Comments