๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Spring

[Spring MVC] Static Resources(์ •์  ๋ฆฌ์†Œ์Šค) ์„ค์ • ๋ฐฉ๋ฒ•

by Leica 2020. 4. 15.
๋ฐ˜์‘ํ˜•

[Spring MVC] Static Resources(์ •์  ๋ฆฌ์†Œ์Šค) ์„ค์ • ๋ฐฉ๋ฒ•

์Šคํ”„๋ง MVC ์›น ํ”„๋กœ์ ํŠธ๋Š” ์ •์  ๋ฆฌ์†Œ์Šค๋ฅผ ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์œผ๋กœ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

์Šคํ”„๋ง XML ์„ค์ •์„ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•๊ณผ WebMvcConfigurer ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

 

์œ„์™€ ๊ฐ™์€ ํ”„๋กœ์ ํŠธ ๊ตฌ์กฐ์—์„œ {ํ”„๋กœ์ ํŠธ ๋ฃจํŠธ}/src/main/webapp/resources ์œ„์น˜์˜ ์ •์  ๋ฆฌ์†Œ์Šค๋ฅผ ์„ค์ •ํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ณด์ž.

์ด resources ๋””๋ ‰ํ† ๋ฆฌ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์Šคํ”„๋ง ์›น ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ์ •์  ๋ฆฌ์†Œ์Šค๋กœ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

1. ์Šคํ”„๋ง MVC ์ •์  ๋ฆฌ์†Œ์Šค XML ์„ค์ • ๋ฐฉ๋ฒ•

ํ”„๋กœ์ ํŠธ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ์Šคํ”„๋ง XML ์„ค์ • ํŒŒ์ผ์—(servlet-context.xml ...) ๋‹ค์Œ ํƒœ๊ทธ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.

 

์Šคํ”„๋ง IoC ์ปจํ…Œ์ด๋„ˆ XML ์„ค์ • ํŒŒ์ผ

<resources mapping="/resources/**" location="/resources/" />
  • mapping : ๋งคํ•‘ URI ์„ค์ •
  • location : ์ •์  ๋ฆฌ์†Œ์Šค ์œ„์น˜ ์„ค์ •

 

2. ์Šคํ”„๋ง MVC ์ •์  ๋ฆฌ์†Œ์Šค WebMvcConfigurer ์„ค์ • ๋ฐฉ๋ฒ•

์Šคํ”„๋ง์ด ์ œ๊ณตํ•˜๋Š” WebMvcConfigurer ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•˜์—ฌ addResourceHandlers()๋ฅผ overrideํ•ด์„œ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

WebMvcConfigurer ๊ตฌํ˜„์ฒด

public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/resources/");
    }
}
  • addResourceHandler() : ๋งคํ•‘ URI ์„ค์ •
  • addResourceLocations() : ์ •์  ๋ฆฌ์†Œ์Šค ์œ„์น˜ ์„ค์ •
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€