GWT та системи управління проектами
DiykoОпубликовано 17.11.2008 в Статьи
Продовження, див. також попередню статтю “Збільш свій прибуток з GWT”.
Коли починаєш писати новий проект і технології всі вибрані, залишається визначитись, що ми будемо використовувати для збирання проекту — Ant чи Maven? Всі інші варіанти розглядати думаю недоцільно, адже саме ці два інструменти є найбільш популярними і часто вживаними на Java проектах. Я для себе визначив, що структурованість Maven-проектів мені більше до вподоби, але наведу приклади конфігураційних файлів для обох систем.
Приклади я робив використовуючи Eclipse, але якщо ви користуєтесь NetBeans або Intellij Idea, то різниці загалом великої не буде, кроки будуть аналогічні.
Отож новий проект на GWT — стягуємо в неті GWT (наразі найновіша версія 1.5.3, але я ще використовую 1.5.2) і розархівовуємо в зручному для вас місці прописуємо GWT_HOME в екліпсі
Window -> Preferences -> Classpath Variables
і environmet variables:
WIN+Break -> Advanced -> Environment Variables

Створюємо новий проект. Для цього запускаємо консоль(Win+R->cmd), заходимо в домашню папку GWT і запускаємо дві команди:
applicationCreator.cmd -eclipse GWT-Example-Ant -out GWT-Example-Ant com.diyko.gwt.example.client.IndexPage
і
projectCreator.cmd -ant build -eclipse GWT-Example-Ant -out GWT-Example-Ant
(Якщо використовується не екліпс, виконуємо ті самі команди тільки без -eclipse GWT-Example-Ant).
Це готовий проект для екліпса з кістяком проекту.
Тепер добавимо пару корисних дрібниць. Створимо в корені проекту папку static і покладемо туди файлик index.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<!-- forward to the GWT Example Application -->
<meta http-equiv="REFRESH" content="0;url=com.diyko.gwt.example.IndexPage/IndexPage.html">
</meta></head>
</html>
Він дозволить не вказувати повний шлях при запуску проекту.
Створимо папку lib і покладемо туди gwt-servlet.jar та додамо його в Build Path.
Створимо папку WEB-INF та покладемо туди web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="GWT-Example-Ant">
<display-name>GWT-Example-Ant</display-name>
</web-app>
Тепер залишилось тільки трішки підправити build.xml або просто замінити на ось такий:
<?xml version="1.0" encoding="utf-8" ?>
<project name="GWT-Example-Ant" default="package" basedir=".">
<description>
GWT-Example-Ant build file. This is used to package up your project as a war,
if you want to distribute it.
</description>
<property environment="env" />
<fail unless="env.GWT_HOME">Please set system property GWT_HOME to folder where you instal Google Web Toolkit</fail>
<!-- path to GWT_HOME -->
<property name="gwt.home" location="${env.GWT_HOME}" />
<property name="on_off" value="on" />
<!-- set classpath -->
<path id="project.class.path">
<pathelement path="${java.class.path}/" />
<pathelement path="${gwt.home}/gwt-user.jar" />
<fileset dir="lib" includes="*.jar" />
<!-- Additional dependencies (such as junit) go here -->
</path>
<target name="compile" description="Compile src to bin">
<echo message="compile web source" />
<mkdir dir="dist/GWT-Example-Ant/WEB-INF/classes" />
<javac srcdir="src" destdir="dist/GWT-Example-Ant/WEB-INF/classes" includes="**" debug="${on_off}" debuglevel="lines,vars,source" source="1.5">
<classpath refid="project.class.path" />
</javac>
</target>
<target name="compileJavaScript" depends="compile" description="Compile src to JavaScript www">
<echo message="compile JavaScript" />
<java classname="com.google.gwt.dev.GWTCompiler" fork="true" failonerror="true" maxmemory="700m">
<arg value="-out" />
<arg value="dist/GWT-Example-Ant" />
<arg value="com.diyko.gwt.example.IndexPage" />
<classpath>
<pathelement path="${java.class.path}" />
<pathelement path="src" />
<pathelement path="${gwt.home}/gwt-user.jar" />
<pathelement path="${gwt.home}/gwt-dev-windows.jar" />
</classpath>
</java>
</target>
<target name="package" depends="compileJavaScript" description="Package up the project as a war">
<echo message="make package" />
<war destfile="dist/GWT-Example-Ant.war" webxml="WEB-INF/web.xml">
<lib dir="lib" />
<fileset dir="dist/GWT-Example-Ant" />
<fileset dir="static" />
</war>
</target>
</project>
Щоб створити GWT аплікацію на Maven потрібно ще менше часу.
Створіть базовий проект за допомогою якогось плагіна в екліпсі, наприклад m2eclipse далі запускаємо консоль(Win+R->cmd), заходимо в домашню папку GWT і запускаємо команду
applicationCreator.cmd -eclipse GWT-Example-Maven -out GWT-Example-Maven com.diyko.gwt.example.client.IndexPage
Копіюємо папку com з папки GWT-Example-Maven/src у наш Maven проект в пакет src/main/java.
(Якщо у вас не екліпс виконуємо те саме тільки без -eclipse GWT-Example-Maven)
Створюємо та копіюємо файлик index.html у папку src/main/webapp/:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<!-- forward to the GWT Example Application -->
<meta http-equiv="REFRESH" content="0;url=com.diyko.gwt.example.IndexPage/IndexPage.html">
</HEAD>
</HTML>
створюємо файлик settings.xml який кидаємо в папку “c:\Documents and Settings\< ваш_логін>\.m2″:
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version
2.0 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 Unless required by
applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for
the specific language governing permissions and limitations under the
License.
-->
<!--
| This is the configuration file for Maven. It can be specified at two
levels: | | 1. User Level. This settings.xml file provides
configuration for a single user, | and is normally provided in
$HOME/.m2/settings.xml. | | NOTE: This location can be overridden with
the system property: | |
-Dorg.apache.maven.user-settings=/path/to/user/settings.xml | | 2.
Global Level. This settings.xml file provides configuration for all
maven | users on a machine (assuming they're all using the same maven
| installation). It's normally provided in |
${maven.home}/conf/settings.xml. | | NOTE: This location can be
overridden with the system property: | |
-Dorg.apache.maven.global-settings=/path/to/global/settings.xml | |
The sections in this sample file are intended to give you a running
start at | getting the most out of your Maven installation. Where
appropriate, the default | values (values used when the setting is not
specified) are provided. | |
-->
<settings>
<profiles>
<profile>
<id>gwt-1.5.2</id>
<properties>
<google.webtoolkit.home>c:\WorkArround\Common\gwt-windows
</google.webtoolkit.home>
<!-- XstartOnFirstThread needed only on the mac -->
<!--
google.webtoolkit.extrajvmargs>-XstartOnFirstThread</google.webtoolkit.extrajvmargs
-->
</properties>
</profile>
<profile>
<id>Snapshots</id>
<repositories>
<repository>
<id>Codehaus Snapshots</id>
<url>http://snapshots.repository.codehaus.org/
</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>Codehaus Snapshots</id>
<url>http://snapshots.repository.codehaus.org/
</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>gwt-1.5.2</activeProfile>
<activeProfile>Snapshots</activeProfile>
</activeProfiles>
</settings>
Для того щоб ми могли компілювати джава код в скрипти та запускати аплікацію в хост режимі з мейвена нам потрібно поправити або замінити pom.xml на:
<?xml version="1.0"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.diyko.gwt</groupId>
<artifactId>example</artifactId>
<packaging>war</packaging>
<name>GWT-Example-Maven</name>
<version>1.0</version>
<properties>
<gwtVersion>1.5.2</gwtVersion>
</properties>
<pluginRepositories>
<pluginRepository>
<id>gwt-maven-plugins</id>
<url> http://gwt-maven.googlecode.com/svn/trunk/mavenrepo/</url>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>gwt-maven</id>
<url> http://gwt-maven.googlecode.com/svn/trunk/mavenrepo/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-user</artifactId>
<version>${gwtVersion}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.gwt</groupId>
<artifactId>gwt-servlet</artifactId>
<version>${gwtVersion}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<finalName>GWT-Example-Maven</finalName>
<plugins>
<!-- configure the GWT-Maven plugin -->
<plugin>
<groupId>com.totsp.gwt</groupId>
<artifactId>maven-googlewebtoolkit2-plugin
</artifactId>
<version>2.0-beta24</version>
<configuration>
<logLevel>INFO</logLevel>
<compileTargets>
<value>com.diyko.gwt.example.IndexPage
</value>
</compileTargets>
<runTarget>com.diyko.gwt.example.IndexPage/IndexPage.html
</runTarget>
<!-- use style DETAILED for js read mode -->
<style>OBF</style>
<noServer>false</noServer>
<extraJvmArgs>-Xmx512m</extraJvmArgs>
<gwtVersion>${gwtVersion}</gwtVersion>
</configuration>
<executions>
<execution>
<goals>
<goal>mergewebxml</goal>
<goal>gwt</goal>
<goal>compile</goal>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>target/web.xml</webXml>
<warSourceExcludes>.gwt-tmp/**</warSourceExcludes>
</configuration>
</plugin>
<!-- tell the compiler we can use 1.5 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Тепер, виконуючи команду mvn install, ви отримуєте варку, яку можна одразу задеплоїти на сервер, а команда mvn gwt:gwt запускає аплікацію в host mode (деталі про можливості та особливості плагіна шукайте за наступним лінком).
В даному випадку я використав ось цей плагін, як на мене він найкращий,
http://code.google.com/p/gwt-maven/
Хоча можливо комусь більше сподобається ось такий наприклад
http://code.google.com/p/mvn-gwt-plugin/w/list
Приклади до статті
Diyko
diykorey@gmail.com
Понравилась статья? Подпишись на обновления по RSS/E-mail



(13 голосов, средний: 3.62 из 5)
думаю, стоило упомянуть, что при использовании maven гвт самостоятельно можно не устанавливать, и GWT_HOME не прописывать. В плагине есть возможность автоскачки GWT и всех необходимых библиотек
Так можна, Ви праві, якщо перейти по лінку можна почитати всі варіанти конфігурації плагіна
Слушне зауваження
Потрібно вибирати не за популярність а за те, як пасує до проекту.
2Максим
це суперечливе твердження
думаю в 99 зі100 випадків вибирають або ант або мейвен і керуються при цьому власним досвідом
А на русский есть перевод статьи?
Разбираюсь с GWT, информации мало.. в статье не понимаю что написано
2Павел:
http://translate.google.com/translate?prev=hp&hl=en&u=http%3A%2F%2Fwww.developers.org.ua%2Farchives%2Fdiyko%2F2008%2F11%2F17%2Fgwt-and-build-systems%2F&sl=uk&tl=ru
Да, могу перевести но нету времени к сожалению, если есть какие то вопроси – обращайтесь ко мне напрямую
Да и перевод то нужно делать не на руский а на английский
Дякую. Мені й не спадало на думку використати applicationCreator.cmd