금융에 대한 모든 것

context.xml

 context.xml 파일은 톰캣에 들어있는 파일로 애플리케이션의 자원을 명시해주는 파일입니다.

context.xml

<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

 톰캣 서버가 실행되면 context.xml 파일의 WatchedResource 태그에 명시된 경로에 따라 web.xml 소스코드를 읽게 됩니다.

 

web.xml

 web.xml은 어플리케이션에 대한 여러 가지 설정을 있는 파일입니다. 아래와 같은 설정 코드들이 들어가고 추가적으로 원하는 설정 코드를 입력할 있습니다.

root-context 경로 설정

<!-- 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>

 코드에서는 param-value 태그를 이용해 설정 파일로 사용될 root-context.xml 위치를 명시해주고 있습니다. 따라서 스프링 프로젝트를 실행할  root-context.xml 설정 정보를 읽어 들이지만 데이터베이스를 연결하지 않았기 때문에 현재는 내용이 비어있습니다.

 

DispatcherServlet 등록, 설정

<!-- 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>

코드에서는 DispatcherServlet이라는 서블릿과 서블릿 설정 파일을 명시하고 있습니다. root-context 마찬가지로 스프링 프로젝트 실행할 servlet-context.xml 설정 정보를 읽어들입니다.

 

필터 설정

<!-- 한글 처리를 위한 인코딩 필터 -->
        <filter>
                <filter-name>encoding</filter-name>
                <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
                <init-param>
                        <param-name>encoding</param-name>
                        <param-value>UTF-8</param-value>
                </init-param>
        </filter>
        <filter-mapping>
                <filter-name>encoding</filter-name>
                <url-pattern>/*</url-pattern>
        </filter-mapping>

기본으로 생성된 프로젝트에는 있지 않지만 한글 처리를 원할하게 하기 위해  필요한 코드입니다. 따라서 위와 같이 utf-8 인코딩 설정을 해주는 코드로 web.xml 추가해야 합니다.

 

servlet-context.xml

servlet.xml은 DispatcherServlet 설정할 있는 파일입니다.

servlet-context.xml

<!-- 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/" />

        <!-- 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.example.spring01" />

<annotatio-driven>은 @Controller 사용할  있도록 설정하는 태그입니다.

 중간에 있는  설정은 @Controller 붙은 클래스에는 접두사로 "/WEB-INF/views/"라는 경로 문자열을 붙여주고 접미사로는 ". jsp"라는 확장자 문자열을 자동으로 붙여주는 설정입니다.

 

<context:component-scan>은 @Controller 붙은 클래스를 모두 탐색할  있는 설정입니다.

 

 위 설명에 관해서는 MVC패턴에서  자세하게 설명하겠습니다.

 

컨트롤러

 컨트롤러는 @Controller라는 어노테이션을 붙은 자바 클래스 파일입니다.

예시

@Controller
public class HomeController {
        
        private static final Logger logger = LoggerFactory.getLogger(HomeController.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 "home";
        }
        
}

우선 컨트롤러에서 핵심적인 기능은 home 메서드가 하고 있습니다. home 메서드가 리턴하는 문자열은 프로젝트를 실행하면 나타나는 웹페이지입니다. 원래는 /WEB-INF/views/home.jsp라는 경로를 나타내는 문자열이 되어야 하지만 servlet-context.xml 설정으로 인해 페이지명만 입력해도 작동이 되는 것입니다. 컨트롤러에 대한 설명은 MVC 패턴에서 자세하게 하겠습니다.

 

jsp 페이지

home.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
        <title>Home</title>
</head>
<body>
<h1>
        Hello world!  
</h1>

<P>  The time on the server is ${serverTime}. </P>
</body>
</html>

컨트롤러의 home 메서드가 리턴한 페이지명이 home이므로 home.jsp 페이지가 화면에 나타나게 됩니다.

 

 

 

 

반응형