Microsoft MVP성태의 닷넷 이야기
Java: 26. IntelliJ + Spring Framework + 새로운 Controller 추가 [링크 복사], [링크+제목 복사]
조회: 9216
글쓴 사람
정성태 (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 예제가 필요한데 그럴 때마다 다른 사람들에게 의존하기가 싫어 맛배기 정도로 다뤄보다가 정리해 본 것입니다.
정성태

... 31  32  [33]  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12803정성태8/23/20218598개발 환경 구성: 600. pip cache 디렉터리 옮기는 방법
12802정성태8/23/20218915.NET Framework: 1102. .NET Conf Mini 21.08 - WinUI 3 따라해 보기 [1]
12801정성태8/23/20218410.NET Framework: 1101. C# 10 - (6) record class 타입의 ToString 메서드를 sealed 처리 허용파일 다운로드1
12800정성태8/22/20218637개발 환경 구성: 599. PyCharm - (반대로) 원격 프로세스가 PyCharm에 디버그 연결하는 방법
12799정성태8/22/20218697.NET Framework: 1100. C# 10 - (5) 속성 패턴의 개선파일 다운로드1
12798정성태8/21/202110031개발 환경 구성: 598. PyCharm - 원격 프로세스를 디버그하는 방법
12797정성태8/21/20217747Windows: 197. TCP의 MSS(Maximum Segment Size) 크기는 고정된 것일까요?
12796정성태8/21/20218414.NET Framework: 1099. C# 10 - (4) 상수 문자열에 포맷 식 사용 가능파일 다운로드1
12795정성태8/20/20219019.NET Framework: 1098. .NET 6에 포함된 신규 BCL API - 스레드 관련
12794정성태8/20/20218485스크립트: 23. 파이썬 - WSGI를 만족하는 최소한의 구현 코드 및 PyCharm에서의 디버깅 방법 [1]
12793정성태8/20/20219176.NET Framework: 1097. C# 10 - (3) 개선된 변수 초기화 판정파일 다운로드1
12792정성태8/19/20219656.NET Framework: 1096. C# 10 - (2) 전역 네임스페이스 선언파일 다운로드1
12791정성태8/19/20217987.NET Framework: 1095. C# COM 개체를 C++에서 사용하는 예제 [3]파일 다운로드1
12790정성태8/18/202110214.NET Framework: 1094. C# 10 - (1) 구조체를 생성하는 record struct파일 다운로드1
12789정성태8/18/20219240개발 환경 구성: 597. PyCharm - 윈도우 환경에서 WSL을 이용해 파이썬 앱 개발/디버깅하는 방법
12788정성태8/17/20217790.NET Framework: 1093. C# - 인터페이스의 메서드가 다형성을 제공할까요? (virtual일까요?)파일 다운로드1
12787정성태8/17/20218015.NET Framework: 1092. (책 내용 수정) "4.5.1.4 인터페이스"의 "인터페이스와 다형성"
12786정성태8/16/20219537.NET Framework: 1091. C# - Python range 함수 구현 (2) INumber<T>를 이용한 개선 [1]파일 다운로드1
12785정성태8/16/20217792.NET Framework: 1090. .NET 6 Preview 7에 추가된 숫자 형식에 대한 제네릭 연산 지원 [1]파일 다운로드1
12784정성태8/15/20217199오류 유형: 757. 구글 메일 - 아웃룩에서 메일 전송 시 Sending' reported error (0x800CCC0F, 0x800CCC92)
12783정성태8/15/20216779.NET Framework: 1089. C# - Indexer에 Range 및 람다 식을 이용한 필터 구현 [1]파일 다운로드1
12782정성태8/14/20216562오류 유형: 756. 파이썬 - 윈도우 환경에서 pytagcloud의 한글 출력 방법
12781정성태8/14/20218725오류 유형: 755. 파이썬 - konlpy 사용 시 JVM과 jpype1 관련 오류
12780정성태8/13/20217100.NET Framework: 1088. C# - 버스 노선 및 위치 정보 조회 API 사용을 위한 기초 라이브러리 [2]
12779정성태8/13/20218969개발 환경 구성: 596. 공공 데이터 포털에서 버스 노선 및 위치 정보 조회 API 사용법
12778정성태8/12/20216235오류 유형: 755. PyCharm - "Manage Repositories"의 목록이 나오지 않는 문제
... 31  32  [33]  34  35  36  37  38  39  40  41  42  43  44  45  ...