IntelliJ에서 Spring Boot 프로젝트는 바로 생성이 되는데
기존 Legacy 형태로 MVC 프로젝트를 만드는 템플릿이 아예 사라진 것 같습니다..
나중의 편의를 위해 maven 프로젝트로 생성해서 Spring MVC 형태를 구현하는 방법을 정리해 보려 합니다.
IntelliJ는 2023.3.2 버전 입니다.
버전 별로 UI가 상이할 수 있습니다.
1. 프로젝트 생성
New Project 선택 후 Maven Archetype을 선택해줍니다.
Archetype 에서 maven-archetype-webapp을 선택 후 Create 해줍니다.
기본 Maven Archetype 프로젝트가 생성됩니다.
기본적으로 생성 후 추가, 수정 작업을 해 주어야 할 부분들이 많습니다.
2. 의존성 주입
우선 pom.xml 파일부터 살펴보면
junit만 dependency 되어 있고 build를 해주는 plugin도 없습니다.
Spring MVC, Servlet/JSP API, jstl 라이브러리 의존성 추가 작업을 해줍니다.
Spring web MVC 버전을 최신버전인 6.1.4로 설정 했습니다.
그에 맞게 servlet은 javax가 아닌 jakarta.servlet을 주입해 주어야 합니다.
Spring MVC는 필수이고 Servlet/JSP API, jstl 라이브러리는 필수는 아닙니다. 보통 MVC 프로젝트에서 클라이언트 JSP 조합으로 많이 사용하니 설정해주도록 하겠습니다.
maven repository 사이트에서 알맞은 버전을 찾아 주입해주면 됩니다.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring</groupId>
<artifactId>springMVC</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>springMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<spring-webmvc-version>6.1.4</spring-webmvc-version>
<jakarta.servlet-api-version>6.0.0</jakarta.servlet-api-version>
<jakarta.servlet-jsp-api-version>3.1.1</jakarta.servlet-jsp-api-version>
<jakarta.servlet.jsp.jstl-api-version>3.0.0</jakarta.servlet.jsp.jstl-api-version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-webmvc-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>${jakarta.servlet-api-version}</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.servlet.jsp/jakarta.servlet.jsp-api -->
<dependency>
<groupId>jakarta.servlet.jsp</groupId>
<artifactId>jakarta.servlet.jsp-api</artifactId>
<version>${jakarta.servlet-jsp-api-version}</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.servlet.jsp.jstl/jakarta.servlet.jsp.jstl-api -->
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>${jakarta.servlet.jsp.jstl-api-version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>springMVC</finalName>
</build>
</project>
3. Web.xml 설정
3.1 Web.xml 스키마 변경
maven-archetype-webapp 프로젝트 생성 시 초기 Web.xml 파일 내용은 아래와 같습니다.
여기서 web-app_2_3.dtd 버전은 EL 문법 사용에 에러가 있습니다. 2.5 버전 이상으로 세팅 해주어야 정상적으로 작동합니다.
- 버전별로 정리되어 있는 참고 글 입니다.
버전(Version)별로 DTD선언 정리 in web.xml
web.xml은 웹서버의 환경설정을 담는 곳으로써 , '배포 설명자'라고도 하며, 웹서버를 구성하는 웹 컴포넌트들에 대한 구성 및 자원의 관계 설정 정보 등을 기술합니다. 특히 URL이 을 어떻게 처리
sayit.tistory.com
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>springMVC Web Application</display-name>
</web-app>
4.0 버전으로 스펙을 변경 해주도록 합니다.
3.2 Dispatcher Servlet 설정
톰캣을 사용하는 자바 웹 어플리케이션은 기본적으로 org.apache.Catalina.servlets.defaultServlet이 클라이언트의 요청을 가장 먼저 받도록 매핑 설정이 되어있습니다.
이를 스프링 MVC의 DispatcherServlet으로 변경하는 설정을 해야합니다.
다음 코드를 web.xml의 <web-app> 태그 내에 추가합니다.
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3.3 Spring MVC Web Context Config 설정
프로젝트 WEB-INF 파일 하위에 config 파일을 생성할 폴더와 dispatcher-servlet.xml 파일을 생성합니다.
폴더명과 파일명은 자유롭게 만들면 됩니다.
ddispatcher-servlet.xml파일 생성 후
web.xml 파일 dispatcherServlet 구문에 <init-param>으로 dispatcher-servlet.xml 경로를 등록해줍니다.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>springMVC Web Application</display-name>
<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/dispatcher-servlet.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>
dispatcher-servlet.xml 파일도 수정해줍니다.
이클립스는 namespace를 선택할 수 있는 설정이 있었던 것 같은데 인텔리제이는 없는 것 같습니다...
여러 설정 방법, 환경 세팅은 해당버전에 해당하는 공식 문서를 찾아보는 것이 좋습니다.
현재 진행하고 있는 Spring Framework 6.1.4 버전 기준의 문서입니다.
https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-config/enable.html
Enable MVC Configuration :: Spring Framework
In Java configuration, you can use the @EnableWebMvc annotation to enable MVC configuration, as the following example shows: In XML configuration, you can use the element to enable MVC configuration, as the following example shows: The preceding example re
docs.spring.io
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"">
</beans>
3.4 Root Context Config 설정
dispatcher-servlet.xml 파일이 있는 경로에 root-context.xml 파일을 생성해 줍니다.
추가 후 web.xml 파일 <web-app> 태그 안에 다음 코드를 넣어줍니다.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3.5 Filter 등록
dispatcher-servlet.xml 에 넘어오는 파라미의 한글이 깨지지 않도록 CharacterEncodingFilter를 등록해줍니다.
<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>
3.6 Web.xml 최종 내용
최종 내용 입니다.
이후 context파일을 추가한 후
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/*.xml</param-value>
</context-param>
아스타를 사용해 여러 파일을 읽을 수 있도록 설정이 가능합니다.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>springMVC Web Application</display-name>
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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/dispatcher-servlet.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>
3. Dispatcher-servlet.xml 설정
3.1 Annotation 사용 설정
dispatcher-servlet.xml 파일에 추가 정보를 등록해 줍니다.
mvc:annotation-driven은 어노테이션 기반의 컨트롤러 및 다른 관련 빈들을 처리할 수 있도록 설정합니다.
이를 통해 @Controller, @RequestMapping 등의 어노테이션을 사용하여 컨트롤러 클래스를 정의하고 요청을 처리할 수 있습니다.
context:component-scan 의 지정된 base-package경로에서 컴포넌트들을 스캔하여 Spring 컨텍스트에 등록되는 Spring Bean으로 등록 해 주는 역할을 합니다.
@Controller, @Service, @Repository, @Component 등의 어노테이션이 붙은 클래스들이 빈으로 등록됩니다.
이를 통해 스프링은 자동으로 컴포넌트들을 찾아서 빈으로 등록하고, 해당 패키지의 클래스들을 스캔하여 알맞은 빈을 생성하게 됩니다.
<!-- annotation 사용 -->
<mvc:annotation-driven />
<!-- component 스캔 할 패키지 경로 -->
<context:component-scan base-package="com.springMVC.project" />
3.2 ViewResolver 설정
이 코드는 Spring MVC에서 JSP(JavaServer Pages) 뷰를 해석하고 렌더링하는 데 사용되는 뷰 리졸버(View Resolver)를 설정하는 역할을 합니다.
- prefix 속성은 JSP 파일의 경로를 지정합니다. /WEB-INF/views/로 설정되어 있으므로, Spring MVC는 JSP 파일을 /WEB-INF/views/ 디렉토리 아래에서 찾게 됩니다.
- suffix 속성은 JSP 파일의 확장자를 지정합니다. .jsp로 설정되어 있으므로, Spring MVC는 JSP 파일을 찾을 때 파일 이름에 .jsp 확장자를 추가하여 찾습니다.
이 설정을 통해 컨트롤러에서 반환하는 뷰 이름과 함께 JSP 파일을 찾고 렌더링할 수 있습니다.
예를 들어, 컨트롤러에서 return "home"과 같은 뷰 이름을 반환하면, 이 뷰 리졸버를 통해 /WEB-INF/views/home.jsp 파일을 찾아 렌더링합니다.
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
3.3 정적 리소스 파일 경로 설정
Spring MVC에서 정적 리소스를 제공하기 위한 설정입니다.
<mvc:resources> 요소를 사용하여 정적 리소스의 매핑 및 위치를 설정합니다:
- mapping 속성은 요청 경로와 매핑할 패턴을 지정합니다. 여기서 /**는 모든 요청에 대해 해당 패턴을 적용한다는 의미입니다. 따라서 모든 요청 경로가 이 패턴과 일치하면 이 정적 리소스 핸들러가 동작합니다.
- location 속성은 정적 리소스 파일들이 위치한 디렉토리를 지정합니다. /resources/로 설정되어 있으므로, Spring MVC는 정적 리소스 파일들을 /resources/ 디렉토리에서 찾게 됩니다.
이 설정을 통해 Spring MVC는 정적 리소스 파일들(css, javascript, 이미지 등)을 요청 경로에 매핑하여 웹 애플리케이션에서 제공할 수 있게 됩니다. 예를 들어, /resources/css/style.css 파일을 요청할 때 Spring MVC는 /resources/ 디렉토리에서 해당 파일을 찾아 반환합니다.
location에 지정된 경로는 webapp 디렉토리를 기준으로 상대적으로 지정됩니다.
location="/resources/"로 되어있으므로 webapp/resources/** 디렉토리에서 정적 파일을 찾게 됩니다.
<mvc:resources mapping="/**" location="/resources/" />
아래는 최종 내용이며 여러 설정들을 더 추가할 수 있습니다.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- annotation 사용 -->
<mvc:annotation-driven />
<!-- component 스캔 할 패키지 경로 -->
<context:component-scan base-package="com.springMVC.project" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/**" location="/resources" />
</beans>
4. Tomcat 설치
Apache Tomcat은 웹 애플리케이션 서버(웹 컨테이너)로서 Java Servlet, JavaServer Pages (JSP) 및 WebSocket과 같은 Java EE 기술을 구현하는 오픈 소스 소프트웨어입니다
Spring Framework으로 개발한 웹 애플리케이션을 실행하려면 웹 애플리케이션 서버가 필요합니다.
servlet Spec에 맞는 톰캣을 설치해 사용해야 합니다.
공식문서에서 확인 후 다운로드 받습니다.
https://tomcat.apache.org/whichversion.html
Apache Tomcat® - Which Version Do I Want?
Apache Tomcat® is an open source software implementation of a subset of the Jakarta EE (formally Java EE) technologies. Different versions of Apache Tomcat are available for different versions of the specifications. The mapping between the specifications
tomcat.apache.org
현재 프로젝트는 servlet 6.0.0 버전을 사용중이기 때문에 10.1.x 버전중 가장 마지막으로 릴리즈 된 10.1.19 버전 톰캣을 다운로드 받았습니다.
다운로드 후 IntelliJ에서 연동해 주시면 됩니다.
4.1 Edit Configurations
Edit Configurations를 찾아 선택해줍니다.
4.2 Tomcat Server
Configurations 화면에서 + 버튼을 선택 후 Tomcat Server 하위의 Local을 선택해줍니다.
화면에서 Configure...버튼 클릭 후 뜨는 창에서 폴더 아이콘을 선택해줍니다.
그 후 다운로드 받았던 tomcat 폴더를 선택하고 OK 버튼을 클릭해주면 톰캣 경로 설정은 끝 입니다.
선택 후 Open browser는 편의에 맞게 Chrome을 선택 해 주었습니다.
서버 실행 시 Chrome을 기본 브라우저로 사용하게 됩니다.
마지막으로 Deplyment 탭 선택 후
Artifacts를 추가해 줍니다.
war exploded를 선택해주시면 되고
Application context를 사용성에 맞게 설정해주시면 되는데 저는 / 경로로 지정했습니다.
완료 되면 톰캣을 실행 해 로컬환경에서 웹 애플리케이션 서버를 구동시킬 수 있습니다.