Gradle 설정
1.eclipse gradle 설정
1) Dashboard 화면 하단에서 Extensions 탭 클릭
2) Find 창에서 gradle 입력 후 Gradle(STS Legacy) Support 항목 선택 후 install

2. gradle의 jre 정보 변경
1) Window – Preferences – Gradle(STS) – Arguments – Java Home 항목을 jdk1.7.x로 변경
3. Gradle 프로젝트 등록
1) 프로젝트 생성 – New -> Other -> Gradle(STS) -> Gradle(STS) Project 선택


4. build.gradle 파일 수정
1) repositories 내용 수정
- 추가해야할 정보 => maven { url "http://repo.spring.io/libs-milestone" }
- 해당 정보를 추가하면 관련 파일을 다운로드한다.
수정 전
repositories { mavenCentral() } |
수정 후
repositories { mavenCentral() maven { url "http://repo.spring.io/libs-milestone" } } |
수정한 기본 build.gradle 정보
apply plugin: 'java' apply plugin: 'eclipse-wtp' apply plugin: 'war' sourceCompatibility = 1.7 targetCompatibility = 1.7 version = '1.0' // 버전 정보 등록 def version = [ spring: '4.1.6.RELEASE', servletAPI: '3.1.0', commonsCollections: '3.2.1', junit: '4.12', slf4j: '1.7.12' ] eclipse { project.natures "org.springsource.ide.eclipse.gradle.core.nature" wtp { facet { facet name: 'jst.web', version: '3.1' facet name: 'jst.java', version: '1.7' } } } jar { manifest { attributes 'Implementation-Title': 'Gradle Quickstart', 'Implementation-Version': version } } repositories { mavenCentral() maven { url "http://repo.spring.io/libs-milestone" } } dependencies {
providedCompile "javax.servlet:javax.servlet-api:${version.servletAPI}" compile "org.springframework:spring-webmvc:${version.spring}" compile "org.slf4j:slf4j-api:${version.slf4j}" compile group: 'commons-collections', name: 'commons-collections', version: "${version.commonsCollections}" testCompile group: 'junit', name: 'junit', version: "${version.junit}" } [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' test { systemProperties 'property': 'value' } uploadArchives { repositories { flatDir { dirs 'repos' } } } |
2) TestGradleProject 선택 후 마우스 오른쪽 버튼 클릭 후 Gradle(STS) – Refresh Dependencies 클릭하면 관련 Module를 다운로드 한다.

5. Springframework 기본 예제 환경 만들기
1) Gradle 프로젝트에서 Java Quickstart로 생성한 패키지 및 파일 삭제

2) src -> main에서 webapp/WEB-INF/views 폴더 생성

3) src/main/webapp/WEB-INF/views/ 폴더 밑에 home.jsp 파일 생성


4) home.jsp에 테스트용 코드 작성
<%@ 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> <h1> Hello Gradle MVC world! </h1> <p> The time on the server is ${serverTime}. </p> </body> </html>
|

5) 프로젝트 마우스 오른쪽 버튼 클릭 -> Run as ->Gradle build.. 클릭

6) Gradle Tasks 명령 입력창에 옵션 명령어 입력 후 Apply -> Run
clean
cleanEclipse
eclipse

빌드 결과

6) 빌드 후 프로젝트에서 F5를 눌러 새로고침을 하게되면 build.gradle에서 의존성 추가해준 라이브러리들이 자동으로 추가

7) 패키지 com.gradle.mvc 생성

8) com.gradle.mvc 패키지 안에 HomeController.java 생성 후 코드 작성
package com.gradle.mvc; import java.text.DateFormat; import java.util.Date; import java.util.Locale; 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 HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! The client locale is {}.", locale); Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); model.addAttribute("serverTime", formattedDate ); return "home"; } } |

9) com.gradle.mvc.config 패키지 생성


10)com.gradle.mvc.config 패키지 안에 AppConfig.java, AppInitializer.java 생성 후 코드 작성

- 컨트롤러에서 편하게 jsp와 맵핑시키기 위해 ViewResolver함수와 리소스 인식을 위한 addResourceHandlers 함수를 작성
package com.gradle.mvc.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import com.gradle.mvc.HomeController; @Configuration @EnableWebMvc public class AppConfig extends WebMvcConfigurerAdapter { @Bean public HomeController homeController(){ return new HomeController(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // TODO Auto-generated method stub registry.addResourceHandler("/resources/**").addResourceLocations( "/resources/"); } @Bean public ViewResolver getViewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } } |

- AppInitializer 에서는 DispatcherServlet 을 설정시켜준다.
package com.gradle.mvc.config; import javax.servlet.Filter; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { // TODO Auto-generated method stub return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { AppConfig.class }; } @Override protected Filter[] getServletFilters() { CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setForceEncoding(true); return new Filter[] { characterEncodingFilter }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } } |

11) 프로젝트 빌드 후 톰캣 실행


이 때 Finish나 Next 버튼이 비활성화 되어 있으면 Project -> Properties -> Project Facets에서 Dynamic Web Module의 버전을 3.1 -> 2.5 변경한다. 변경이 불가능할 경우
(이클립스에서 프로젝트를 Import 한 후에 서버를 연결하려고 할때 "Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 WEb modules" 라는 오류가 나오는 경우에도 해당)
- 위 경우는 Web Module 3.1 에서 Tomcat 7.0을 연결하려고 한 증상
.settings -> org.eclipse.wst.common.project.facet.core.xml 파일을 열어서 jst.web 항목의 값을3.1=>2.5로 직접 수정한다.

12) 이클립스 재시작 후 프로젝트 빌드 후 Run AS -> Run on Server으로 시작 또는 톰캣 서버를 실행한 후 직접 URL을 입력하여 확인(http://localhost:8080/TestGradleProject/)

환경 참고 사이트 : http://stag.tistory.com/22?category=614898
오류 관련 참고 사이트 : http://roadrunner.tistory.com/603
Gradle 버전 관련 참고 사이트 : https://code.i-harness.com/ko/q/ee4c92