Microsoft MVP성태의 닷넷 이야기
Java: 26. IntelliJ + Spring Framework + 새로운 Controller 추가 [링크 복사], [링크+제목 복사]
조회: 9193
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

IntelliJ + Spring Framework + 새로운 Controller 추가 예제

이것저것 만지다 보니 IntelliJ의 프로젝트 관리가 좀 불편한 점이 눈에 띄는군요. IntelliJ는 IDE로서 동작하고 관련된 프로젝트 정보를 ".idea" 디렉터리 하위에 각종 파일 및 또 다른 디렉터리로 저장합니다. 그리고, 이와 함께 자바 프로젝트는 의존성 빌드를 위한 pom.xml 파일이 별도로 있습니다.

그러니까, 닷넷과 비교하면 csproj 파일 하나가 ".idea" + "pom.xml"로 쪼개져 있는 거라고 보시면 됩니다. 게다가 csproj는 노출되어 있어 개발자가 언제든 직접 편집할 정도로 친숙한 반면, ".idea"는 (점으로 시작하는 디렉터리는 숨김 효과를 갖죠!) 그 체계를 이해하기에는 csproj에 비해 너무 복잡합니다.

또한, ".idea"와 "pom.xml"은 별개로 유지/확장하고 있기 때문에 서로 따로 노는 듯합니다. csproj/msbuild 사용자로서 다소 이해가 안 되는 부분이 있다면, IntelliJ IDE에서 특정 디렉터리를 빌드 제외했는데 그것이 pom.xml에는 전혀 기록되지 않고 ".idea"에 유지된다는 점입니다. 그렇다면, maven compile을 해도 개발자가 빌드 제외한 것을 무색하게 그냥 모두 빌드하는 것과 다를 바가 없을 듯한데... (아직 제가 이 분야는 초보라서 더 깊이 논의하는 것이 좀 의미가 없을 것 같습니다. ^^)

그나저나, IntelliJ의 ".idea" 관리에도 신뢰가 잘 가지 않습니다. 실제로 제가 최근 들어 IntelliJ + Spring 예제 작성을 하면서 프로젝트의 관리의 어디가 잘못된 것인지 분간도 안 되고, 심지어 어디가 꼬여버렸는지 알 수 없어 차라리 프로젝트 정보(.idea)를 삭제하고 다시 import하는 것으로 문제를 해결하기도 했습니다. (물론, 제가 뭔가를 잘못한 게 있긴 하겠지요. ^^; 그렇다 해도 숙련된 개발자도 헷갈릴 정도라면 분명히 문제가 있어 보입니다.)

암튼, 이번 글은 그래서 쓰게 되었습니다. ^^




자, 그럼 제목에 알맞은 글을 써 볼까요? ^^ 우선, 새로운 프로젝트를 하나 다음의 설정으로 생성합니다.

Name: spring-sample-05
Location: d:\intellij\spring-sample-05
Artifact Coordinates
    - GroupId: org.example
    - ArtifactId: spring-sample-05
    - Version: 1.0-SNAPSHOT

Add Framework Support: Spring MVC(5.2.3.RELEASE)

이 상태에서 몇 가지 경고를 해결하기 위한 설정과 spring framework 관련 설정을 pom.xml에 추가합니다.

// pom.xml

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>5.2.3.RELEASE</spring.version>
    </properties>

    <packaging>war</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
                <configuration>
                    <webXml>web\WEB-INF\web.xml</webXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>

그다음, 원한다면 spring controller가 "/"에서도 매핑이 되도록 ./web/WEB-INF/web.xml 파일의 내용을 하나 수정하고,

// web.xml

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

마지막으로 ./web/WEB-INF/applicationContext.xml 파일의 내용을 다음과 같이 채워줍니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" >

    <mvc:annotation-driven />
    <context:component-scan base-package="org.example" />

    <bean id="contentNegotiatingViewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/views/" />
                    <property name="suffix" value=".jsp" />
                </bean>
            </list>
        </property>
    </bean>
</beans>

위에서 context:component-scan의 base-package를 "org.example"로 했기 때문에 이제 ./src/main/java 디렉터리 하위에 controller가 추가될 패키지를 "org.example.controller"로 생성한 다음 HomeController.java 파일 하나를 추가합니다.

package org.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/")
public class HomeController {

    @RequestMapping
    public String home(Model model) {
        model.addAttribute("var1", "World");
        return "hello";
    }
}

그리고 위에서 "hello" 뷰를 반환하기 때문에 ./web/WEB-INF 하위에 (applicationContext.xml의 prefix/suffix 설정에 따라) "views" 디렉터리를 생성하고 hello.jsp를 만듭니다.

<%@ page contentType="text/html;charset=UTF-8" language="java"
         import="org.springframework.core.SpringVersion" %>
<html>
<head>
    <title></title>
</head>
<body>
SpringVersion: <% out.println(SpringVersion.getVersion()); %> <br />
Hello, ${var1}
</body>
</html>

또한, "/" 경로에서 controller를 매핑할 것이기 때문에 "./web/index.jsp" 파일이 필요 없으므로 삭제합니다.




일단, 위의 과정까지만 진행했으면 이제 새로운 Run/Debug Configuration을 추가하고 실행하면 정상적으로 Controller 출력이 나와야 할 것입니다. 그런데, 저 상태에서 실행해 보면 정상적으로 동작하지 않습니다. 뭔가 더 복잡한(또는 제가 알지 못하는 쉬운) 방법이 있는지 모르겠지만 그건 제쳐 두겠습니다.

이제 (제가 생각하기에 쉬운 방법으로 해결하기 위해) 잠시 프로젝트를 종료하고, ./spring-sample-05 디렉터리로 이동해 "src", "web" 디렉터리와 pom.xml 파일만 남기고 모두(.idea, lib, target 디렉터리와 spring-sample-05.iml 파일 등) 삭제합니다.

이후 다시 IntelliJ를 실행하고 ./spring-sample-05/pom.xml 파일을 프로젝트 유형으로 엽니다.

그다음, "File" / "Project Structure... (Ctrl + Shift + Alt + S)" 메뉴를 선택하고, "Project Settings" / "Modules" 범주의 "spring-sample-05" / "Web" 항목에 있는 "Web Resource Directory" 경로를 수정합니다.

spring_new_controller_1.png

기존: d:\intellij\spring-sample-05\src\main\webapp (오류가 있는 경로이므로 빨간색으로 표시됨)
신규: d:\intellij\spring-sample-05\web

마지막으로 프로젝트 실행을 위해 "Run/Debug Configuration"을 하나 추가해 Deployment의 "Deploy at the server startup"과 "Application context" 항목을 설정하고,

Tomcat Server - Local
    Server
        Before launch: 
            Build
            Build 'spring-sample-05:war exploded' artifact
    Deployment
        Deploy at the server startup
            spring-sample-05:war exploded
        Application context: /

"F5" 실행을 하면 정상적으로 "GET /" 요청에 대해 HomeController와 hello.jsp의 연동 결과가 화면에 출력될 것입니다. ^^

또한, 이렇게 하고 "maven package"로 war를 출력하면 크기도 기존 3KB에서 5.5MB로 (spring을 품은 듯한) 정상적인 크기로 나옵니다.

(첨부 파일은 위의 내용대로 구성한 예제 프로젝트입니다.)




maven compile에서 이런 오류가 발생한다면?

package org.springframework.stereotype does not exist
package org.springframework.ui does not exist
package org.springframework.web.bind.annotation does not exist
...기타: cannot find symbol...

각각의 package 참조를,

org.springframework.stereotype - org.springframework/spring-context 
org.springframework.web.bind.annotation, org.springframework.ui - org.springframework/spring-web

pom.xml에 추가합니다.

// pom.xml

// ...[생략]...

<properties>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <spring.version>5.2.3.RELEASE</spring.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
</dependencies>

위에서 "5.2.3.RELEASE" 버전은 IntelliJ에서 "Add Framework Support..."로 추가한 Spring Framework의 버전을 가져온 것인데 이것은 프로젝트 경로의 './.idea/libraries' 경로에서 구할 수 있습니다.




IntelliJ에서 import 후 pom.xml 내용이 초기화되었다면? 아마도 여러분은 pom.xml을 프로젝트 유형으로 열은 것이 아니고, pom.xml이 포함된 디렉터리를 IntelliJ에서 열었을 것입니다. 그런 경우에는 pom.xml이 초기화되니, 위의 내용에 따라 다시 입력해 주면 됩니다.




<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="com.spring" />
</beans>

위와 같은 설정에서 실행 시 이런 오류 로그가 발생하는데요,

07-Aug-2021 23:52:54.826 SEVERE [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.ContextLoader.initWebApplicationContext Context initialization failed
    org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 8 in XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 8; columnNumber: 30; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:annotation-driven'.
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:405)
        ...[생략]...
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:435)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:393)
        ... 60 more

schemaLocation의 값이 불충분해서 발생한 오류입니다. 이렇게 바꾸면 정상적으로 실행됩니다.





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/11/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-08-11 01시01분
[Lyn] 요즘은 ant / maven 프로젝트보단 gradle 프로젝트를 더 많이 쓰는데 그쪽 글도 써주세요
[guest]
2021-08-11 09시33분
아니... 저같은 자알못에게 그렇게까지 기대하시면 안 됩니다. ^^ 위의 글도 그냥... Spring 예제가 필요한데 그럴 때마다 다른 사람들에게 의존하기가 싫어 맛배기 정도로 다뤄보다가 정리해 본 것입니다.
정성태

1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13456정성태11/25/20232553닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232454닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232811닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232315오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232419닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232549닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232358닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232425개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232668닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232552닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232481닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232810Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232553닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232603개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232424개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232730닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232410Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232916닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232514닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232708닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232961닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232888닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232657스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232371스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232441오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232773스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...