거누의 개발노트

Eclipse+Gradle+Spring 웹 프로젝트 만들기! (이클립스, 그래들, 스프링) - [Web Project] 1편 본문

Web

Eclipse+Gradle+Spring 웹 프로젝트 만들기! (이클립스, 그래들, 스프링) - [Web Project] 1편

Gogozzi 2020. 12. 31. 16:43
반응형

(매번 환경설정 할 때마다 헷갈리는 경우가 많아 정리하려고 한다.)

STS를 이용하는 방식과 조금 다릅니다. 이점 참고 ^0^ ( 최대한 간단 설치하고, 컴팩트하게 생성하려고 했습니다. )

이클립스에서 그래들로 빌드해 스프링 프레임워크 기반으로 Web Application을 만들어 보자!

제일 먼저해야할 일은 이클립스, JAVA(JDK), 톰캣 설치이다. 

 

JAVA 설치는 아래링크에서 하면 된다.

geonoo.tistory.com/7

 

윈도우에 자바 설지 - Window Java Install [개발 노트]

Windows 10 Java 설치 Windows 10에 자바(JDK 1.8)를 설치 해보겠습니다. Tomcat 이나, 오라클 데이터베이스를 설치 및 이용하려면 JDK가 필요합니다. https://www.oracle.com/java/technologies/javase/javase-jd..

geonoo.tistory.com

 

톰캣설치는 아래링크에 가서 자신의 환경에 맞는 ZIP 파일을 설치한다. 

tomcat.apache.org/download-80.cgi

 

Apache Tomcat® - Apache Tomcat 8 Software Downloads

Welcome to the Apache Tomcat® 8.x software download page. This page provides download links for obtaining the latest versions of Tomcat 8.x software, as well as links to the archives of older releases. Unsure which version you need? Specification versions

tomcat.apache.org

 

이클립스 설치는 아래링크에서 설치하자!

www.eclipse.org/downloads/

 

Eclipse Downloads | The Eclipse Foundation

The Eclipse Foundation - home to a global community, the Eclipse IDE, Jakarta EE and over 375 open source projects, including runtimes, tools and frameworks.

www.eclipse.org

 

[목차]

1. Gradle Project 생성
2. build.gradle 수정하기!
3. Project 설정 (Web Module, java 설정 등)
4. 패키지 생성, MainController 생성
5. 서버 생성!
6. Project library 추가
7. web 설정, spring 설정 파일 만들기 ( web, servlet )
8. MainController 수정, jsp 만들기!
9. 서버 시작!

* 다 읽으시지 마시고 보고싶은 부분만 읽으세요.

 

1. Gradle Project 생성

👉 이클립스를 실행하자

 

👉  File -> New -> Other... 클릭!

 

👉 Gradle 찾아주시구 Next!

 

👉 Next

 

👉 Finish

 

👉 그래들 프로젝트 생성 완료!

 

 

2. build.gradle 수정하기!

👉 build.gradle

 

//언어
apply plugin: 'java'
apply plugin: 'war'

//JDK 버전 설정
sourceCompatibility = 1.8
targetCompatibility = 1.8

//라이브러리 저장소
repositories {
    jcenter()
}

//인코딩
tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}


//의존성 ; 외부 라이브러리
dependencies {
	testCompile fileTree(dir: 'WebContent/WEB-INF/lib', include: ['*.jar'])
	compile fileTree(dir: 'lib', include: ['*.jar'])
	compile 'ch.qos.logback:logback-classic:1.2.2'
}

//프로젝트 폴더 이름
//war 설정
project.webAppDirName = 'WebContent'
war {
	archiveName = "${baseName}.${extension}"
}

👉 build.gradle 위에 복사 후 붙여넣기! 저장해줍니다.

 

3. Project 설정 (Web Module, java 설정 등)

👉 프로젝트 우클릭 -> Properties 클릭해 줍니다.

 

👉 Project Facets -> Convert to faceted form... 클릭!

 

👉 Dynamic Web Module 체크, Java 체크(본인이 설치한 버전), JavaScript 체크

 

4. 패키지 생성, MainController 생성

👉 package 만들기!

👉 controller, service, vo 패키지 생성전에있던 패키지는 삭제해줍니다.

 

👉 controller 패키지 안에 MainController.java 파일 하나 만들어줍니다.

 

 

5. 서버 생성!

👉 해당 링크 클릭 하거나, 마우스 우클릭 -> New -> Server 클릭

👉 설치한 톰캣 버전에 맞춰서 선택 -> Server name 설정 -> Next

 

👉 Tomcat 설치된 경로 선택 -> JRE 선택 -> Finish [서버 생성 완료!]

 

 

6. Project library 추가

👉 Project 우클릭 -> Properties 클릭 -> Java Bulid Path

 

👉 오른쪽에 Add Library... -> Server Runtime -> Next

 

👉 아까 설정한 server(test) 선택 후 Finish !

 

👉 Apache Tomcat v8.5[test] 라이브러리 들어온것을 확인 후 Apply and Close 클릭!

 

 

7. web 설정, spring 설정 파일 만들기 ( web, servlet )

👉 5번에서 서버를 생성하면 Servers라는 폴더안에 내가 만든 서버의 설정 파일들이 보입니다.

👉 설정파일 중 context.xml을 열어서 웹 어플리케이션의 자원을 어디에 할 것인지 디폴트 경로가 설정되어있습니다.

👉 그렇다면 해당 경로에 web.xml을 작성해 보겠습니다.

 

👉 프로젝트 -> WebContent -> WEB-INF -> spring 폴더와 web.xml을 만든다.

👉 spring 폴더 안에는 appServlet 폴더와 root-context.xml 폴더를 만든다.

👉 appServlet 폴더 안에는 application-context.xml, dispatcher-servlet.xml, servlet-context.xml

글로는 표현하기 어려우니 아래 캡처 화면대로 만들어주시면 됩니다.

 

👉 WebContent/WEB-INF/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" version="3.0">
  <!-- 프로젝트 이름  -->
  <display-name>test</display-name>
  
  <!-- root-context 설정  -->
  <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, application, dispatcher 설정  -->
  <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/appServlet/*.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>
  
  <!-- Encoding  -->
  <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>
  
  <!-- Error 설정 -->
  <error-page>
    <error-code>400</error-code>
    <location>/WEB-INF/views/error.jsp?code=400</location>
  </error-page>
  <error-page>
    <error-code>401</error-code>
    <location>/WEB-INF/views/error.jsp?code=401</location>
  </error-page>
  <error-page>
    <error-code>403</error-code>
    <location>/WEB-INF/views/error.jsp?code=403</location>
  </error-page>
  <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/error.jsp?code=404</location>
  </error-page>
  <error-page>
    <error-code>405</error-code>
    <location>/WEB-INF/views/error.jsp?code=405</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/WEB-INF/views/error.jsp?code=500</location>
  </error-page>
  <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/WEB-INF/views/error.jsp</location>
  </error-page>
  
</web-app>

 

👉 WebContent/WEB-INF/spring/root-context.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:p="http://www.springframework.org/schema/p"
        xmlns:jee="http://www.springframework.org/schema/jee"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
  
        
</beans>

 

👉 WebContent/WEB-INF/spring/appServlet/application-context.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:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<bean id="cnManager"
		  class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
		<property name="favorPathExtension" value="true"/>
		<property name="ignoreAcceptHeader" value="true" />
		<property name="defaultContentType" value="text/html" />
		<property name="useJaf" value="false"/>

		<property name="mediaTypes">
		  <map>
			<entry key="html" value="text/html" />
			<entry key="json" value="application/json" />
			<entry key="xml" value="application/xml" />
		  </map>
		</property>
	</bean>
	
</beans>

 

👉 WebContent/WEB-INF/spring/appServlet/dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	
	<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<beans:property name="basename" value="classpath:language/Message" />
		<beans:property name="defaultEncoding" value="UTF-8" />
	</beans:bean>

	<beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
		<beans:property name="defaultLocale" value="ko" />
	</beans:bean>

	<interceptors>
		<beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
			<beans:property name="paramName" value="locale" />
		</beans:bean>
	</interceptors>

</beans:beans>

 

👉 WebContent/WEB-INF/spring/appServlet/servlet-context.xml

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

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/static/**" location="/static/" />
    
	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/view/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	
	<context:component-scan base-package="controller" />
	<context:component-scan base-package="service" />
	
</beans:beans>

👉 위 스크립트를 복사 저장 해줍니다.

👉 view, static 폴더 미리 만들어줍니다. ( 경로에 맞게 )

 

8. MainController 수정, jsp 만들기!

package controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MainController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	

	public MainController() {
		logger.info("MainController");
		logger.info("start test Server...");
	}
	
	@RequestMapping(value = {"", "/", "index"}, method = RequestMethod.GET)
    public String index(HttpServletRequest HttpRequest, HttpSession session, Locale locale, Model model) {
		logger.info("index page...");
		
		return "index";
    }
	
}

👉 위 와 같이 MainController.java 수정해줍니다.

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h2>안뇽하세요 케케케</h2>
</body>
</html>

👉 index.jsp 파일 하나 만들어줍니다.

 

9. 서버 시작!

👉 프로젝트 우클릭 -> Run As -> Run on Server 클릭

 

 

 

 

끝~~

 

나누어서 하려고 했는데 하다 보니 길어졌네요 ... ଘ(੭*ˊᵕˋ)੭ 

 

다음은 DB, Mybatis 관련해서 작성 해봐야겠다...

반응형
Comments