Microsoft MVP성태의 닷넷 이야기
Java: 26. IntelliJ + Spring Framework + 새로운 Controller 추가 [링크 복사], [링크+제목 복사]
조회: 9076
글쓴 사람
정성태 (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)
13373정성태6/19/20234398오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233111개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233132개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233295개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233092개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233225개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233332오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233130.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232896오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233677.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233241스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233164.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233638오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233036오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233352오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233660.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233464.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233769DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233685.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233957.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233569.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234070VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233322오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233661.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233570.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20233932.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...