본문 바로가기
☕Java/Java EE(Jakarta EE)

web.xml이란?

by 캔 2022. 6. 19.

앞서 자바 웹 애플리케이션 구조를 살펴보았다.(https://lifewithcoding.tistory.com/207) 웹 애플리케이션 구조에서 보았던 web.xml 파일에 대해 자세히 알아보자.

 

자바 웹 애플리케이션을 빌드하여 패키징한 war 파일 내부를 보면 web.xml 파일이 존재한다. 이 web.xml 파일은 배포 기술서(Deployment Descriptor)라고도 하는데, 웹 애플리케이션을 실행할 때 필요한 설정들을 담고 있다.

 

web.xml에 서블릿, 필터, 리스너를 등록할 수 있다. 웹 애플리케이션은 요청이 들어오면 그 요청을 수행할 컨트롤러를 찾아 작업을 수행하도록 하고 그 결과를 응답으로 전송한다. 그 과정에서 어떤 URI로 요청이 들어왔을 때 어느 서블릿에게 요청을 전달할 것인지 매핑을 한다. 서블릿 버전 1.x대에서는 서블릿 코드를 작성하고 URI 주소 값을 각각의 서블릿에 일일이 매핑을 해줘야 했기 때문에 개발자들이 XML을 작성하는데 많은 시간과 노력을 들여야 했다 하지만 서블릿 2.0이 출시되고 나서 서블릿에 @WebServlet 애너테이션만 달아주면 매핑이 끝나게 되어 간편해졌다. 서블릿 스펙 버전이 올라감에 따라 웹 애플리케이션 설정 방식도 개발자 친화적으로 바뀌어 왔는데 3.0 이후에는 자바 기반 설정도 지원하게 되어 XML 없이도 웹 애플리케이션에 대한 설정이 가능하게 되었다. 이에 대해서도 이후의 포스팅에서 다룰 예정이다.

 

다음은 web.xml의 엘리먼트들을 나열한 것이다.(알파벳순) - https://docs.oracle.com/cd/E13222_01/wls/docs81/webapp/web_xml.html를 참조함.

  • context-param
  • description
  • distributable
  • ejb-ref
  • ejb-local-ref
  • env-entry
  • error-page
  • env-entry
  • filter
  • filter-mapping
  • icon
  • listener
  • login-config
  • mime-mapping
  • resource-env-ref
  • security-constraint
  • security-role
  • servlet
  • servlet-mapping
  • session-config
  • taglib
  • welcome-file-list

이 중에서 굵은 색 글씨들이 실무에서 자주 쓰이는 엘리먼트들이다. servlet, servlet-mapping은 서블릿 관련, filter, filter-mapping은 필터 관련, listener는 리스너 관련 설정 태그이다. 보안 관련해서 security-constraint나 login-config, session-config 설정을 사용하기도 한다. welcome-file-list는 웹사이트의 루트 페이지 접근 시에 보여줄 정적 리소스를 설정하는 엘리먼트이다.

 

아래는 실무에서 자주 보게 되는 기본적인 web.xml의 형태이다.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebPress" version="3.0">
    <display-name>(프로젝트 이름)</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            (루트 컨텍스트 경로)
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                (서블릿 컨텍스트 경로)
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <login-config>
        <auth-method>BASIC</auth-method>
    </login-config>

    <session-config>
        <session-timeout>(세션 타임아웃 시간(분))</session-timeout>
        <cookie-config>
            <http-only>true</http-only>
        </cookie-config>
    </session-config>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Restricted HTTP methods.</web-resource-name>
            <url-pattern>/*</url-pattern>
            <http-method>PUT</http-method>
            <http-method>DELETE</http-method>
            <http-method>TRACE</http-method>
            <http-method>OPTIONS</http-method>
        </web-resource-collection>
        <auth-constraint/>
    </security-constraint>

    <error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>(에러 페이지 경로)</location>
    </error-page>
    <error-page>
        <error-code>400</error-code>
        <location>(에러 페이지 경로)</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>(에러 페이지 경로)</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>(에러 페이지 경로)</location>
    </error-page>
    <error-page>
        <error-code>503</error-code>
        <location>(에러 페이지 경로)</location>
    </error-page>
</web-app>