옹실이의 개발이야기

Spring

Spring : jsp 호출 원리 - Web.xml, root-context.xml, servlet-context.xml

옹실 2023. 2. 4. 16:48

최근 토이 프로젝트를 진행하면서 스프링에 대해 다시 공부하게 되었다.

스프링 MVC 프로젝트를 만들고 실행하면
index.jsp를 호출하게 되는데, 어떤 원리로 jsp 페이지를 호출하게 되는걸까?

①web.xml -> ②servlet-context.xml -> ③IndexController.java -> ④index.jsp
순서로 index.jsp 가 호출된다

 

① web.xml

web.xml은 웹 프로젝트 설정 파일로
WAS가 처음 구동되면 web.xml을 읽어 설정을 구성한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
</web-app>
 
cs


클라이언트가 요청을 하면 가장 먼저 web.xml 안에 있는 태그를 읽어들이면서
<listener>의 ContextLoaderListener 클래스를 이용해 contextConfigLocation 에 있는 root-context.xml 를 불러오고,
스프링에 내장되어있는 컨트롤러인 dispatcherServlet를 이용해 servlet-context.xml 파일을 실행하게 된다.

※ dispatcherServlet
스프링에 내장되어있는 컨트롤러로 클라이언트의 요청을 핸들링하는 역할을 한다.
MVC 패턴에서 Model, View, Controller 파트를 조합해 브라우저로 출력해주는 클래스라고 보면 된다.

 

root-context.xml

스프링의 환경설정 파일로, 이 context에 등록되는 Bean들은 모든 context에서 사용되어 진다.(공유가 가능하다)

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
        
</beans>
 
cs

여기선 별다른 설정을 하지 않았기 때문에 특별히 거치는 과정이 없다.

 

 servlet-context.xml

servlet-context.xml은 DispatcherServlet 등록 시 설정한 파일로
스프링에서 자바 객체(Bean)를 관리하는 공간인 스프링 컨테이너를 초기화한다.

※ 스프링 컨테이너
자바 객체를 스프링에선 빈(Bean)이라고 하는데,
스프링 컨테이너에서 이 빈의 생성부터 소멸까지 관리해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
 
    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />
 
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />
    
    <!--  ressources/js라고 안하고 걍 /js로 바로 적어서 접근하게따 -->
    <resources mapping="/js/**" location="/resources/js/" />
    <resources mapping="/fonts/**" location="/resources/fonts/" />
    <resources mapping="/css/**" location="/resources/css/" />
    <resources mapping="/scss/**" location="/resources/scss/" />
    <resources mapping="/img/**" location="/resources/img/" />
    <resources mapping="/lib/**" location="/resources/lib/" />
 
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
    
    <context:component-scan base-package="com.eventer.service" />
    
    
    
</beans:beans>
 
cs

servlet-context.xml에서 기본 패키지로 지정한 com.eventer.service를 스캔해서
해당 패키지 안에 있는 indexController.java 파일을 참조하게 되고,
indexController.java 안에 애노테이션으로 명시한 클래스를 context에 빈으로 등록해준다.
(참고로 여기서 등록된 Bean들은 servlet-container에만 사용되어진다.)

servlet-context.xml에 기본적인 접두어(prefix), 접미어(suffix) 설정을 해주면
컨트롤러에서 jsp파일 호출 시 .jsp를 빼고 파일명만으로 jsp를 사용할 수 있다.
ex) return "/WEB-INF/view/index.jsp";  -->  return "index";

( indexController에서 index.jsp파일 호출 시 .jsp를 빼고 "index" 로 사용할 수 있는 이유가 이것 때문이다. )

 

④ indexController.java

indexController.java로 넘어오면 개발자가 해당 클래스 내에 구현한 다양한 로직을 거쳐
최종적인 view index 페이지를 return하게 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.eventer.service;
 
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
/**
 * Handles requests for the application home page.
 */
@Controller
public class indexController {
    
    private static final Logger logger = LoggerFactory.getLogger(indexController.class);
    
    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
        
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        
        String formattedDate = dateFormat.format(date);
        
        model.addAttribute("serverTime", formattedDate );
        
        return "index";
    }
    
}
 
cs

 

참고
doublesprogramming.tistory.com/84

kingofbackend.tistory.com/77