developer tip

전쟁 파일을 만드는 방법

optionbox 2020. 8. 30. 08:11
반응형

전쟁 파일을 만드는 방법


Tomcat에서 실행하기 위해 (Eclipse를 사용하여) war 파일을 만드는 모범 사례는 무엇입니까? 튜토리얼, 링크, 예제는 높이 평가됩니다.


Ant사용 하여 솔루션 을 설정, 컴파일, WAR 및 배치 할 수 있습니다.

<target name="default" depends="setup,compile,buildwar,deploy"></target>

그런 다음 Eclipse에서 한 번의 클릭을 실행하여 해당 Ant 대상을 실행할 수 있습니다. 다음은 각 단계의 예입니다.

전제 조건

코드가 다음과 같이 구성되어 있다고 가정합니다.

  • ${basedir}/src: Java 파일, 속성, XML 구성 파일
  • ${basedir}/web: JSP 파일
  • ${basedir}/web/lib: 런타임에 필요한 모든 JAR
  • ${basedir}/web/META-INF: 매니페스트
  • ${basedir}/web/WEB-INF: web.xml 파일

설정

setup배포 디렉토리를 생성하고 WARred가 필요한 아티팩트를 직접 복사 하는 작업을 정의합니다 .

<target name="setup">
    <mkdir dir="dist" />
    <echo>Copying web into dist</echo>
    <copydir dest="dist/web" src="web" />
    <copydir dest="dist/web/WEB-INF/lib" src="${basedir}/../web/WEB-INF/lib" />
</target>

엮다

Java 파일을 클래스로 빌드하고 그 아래에 src있지만 런타임에 사용할 수 있어야 하는 비 Java 아티팩트 (예 : 속성, XML 파일 등)를 복사합니다 .

<target name="compile">
    <delete dir="${dist.dir}/web/WEB-INF/classes" />
    <mkdir dir="${dist.dir}/web/WEB-INF/classes" />
    <javac destdir="${dist.dir}/web/WEB-INF/classes" srcdir="src">
        <classpath>
            <fileset dir="${basedir}/../web/WEB-INF/lib">
                  <include name="*" />
            </fileset>
        </classpath>
    </javac>
    <copy todir="${dist.dir}/web/WEB-INF/classes">
        <fileset dir="src">
            <include name="**/*.properties" />
            <include name="**/*.xml" />
        </fileset>
    </copy>
</target>

WAR 빌드

WAR 자체를 작성하십시오.

<target name="buildwar">
    <war basedir="${basedir}/dist/web" destfile="My.war"
     webxml="${basedir}/dist/web/WEB-INF/web.xml">
        <exclude name="WEB-INF/**" />
        <webinf dir="${basedir}/dist/web/WEB-INF/">
            <include name="**/*.jar" />
        </webinf>
    </war>
</target>

배포

마지막으로 Tomcat 배포 위치에 WAR를 직접 배포하는 작업을 설정할 수 있습니다.

<target name="deploy">
    <copy file="My.war" todir="${tomcat.deploydir}" />
</target>

클릭하고 가십시오!

이 모든 것이 설정되면 defaultEclipse 에서 대상을 실행하기 만하면 솔루션이 컴파일, WAR 및 배포됩니다.

이 접근 방식의 장점은 Eclipse 내에서뿐만 아니라 Eclipse 외부에서도 작동하며 프로젝트 작업을 수행하는 다른 개발자와 배포 전략 (예 : 소스 제어를 통해)을 쉽게 공유하는 데 사용할 수 있다는 것입니다.


저는 항상 Eclipse에서 내보내기를 선택했습니다. war 파일을 빌드하고 필요한 모든 파일을 포함합니다. 프로젝트를 웹 프로젝트로 생성 한 것을 제공하기 만하면됩니다. Eclipse를 사용하면 매우 간단합니다.


우리는 모든 자바 프로젝트에 Maven (Ant의 큰 형제)을 사용하며 매우 멋진 WAR 플러그인을 가지고 있습니다. 튜토리얼과 사용법은 거기에서 찾을 수 있습니다.

Ant보다 훨씬 쉽고 Eclipse와 완벽하게 호환되며 ( 이클립스 프로젝트를 만들려면 maven eclipse : eclipse 를 사용) 구성하기 쉽습니다.

Maven의 홈페이지

Maven WAR 플러그인

샘플 구성 :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1-alpha-2</version>
    <configuration>
        <outputDirectory>${project.build.directory}/tmp/</outputDirectory>
        <workDirectory>${project.build.directory}/tmp/war/work</workDirectory>
        <webappDirectory>${project.build.webappDirectory}</webappDirectory>
        <cacheFile>${project.build.directory}/tmp/war/work/webapp-cache.xml</cacheFile>
        <nonFilteredFileExtensions>
            <nonFilteredFileExtension>pdf</nonFilteredFileExtension>
            <nonFilteredFileExtension>png</nonFilteredFileExtension>
            <nonFilteredFileExtension>gif</nonFilteredFileExtension>
            <nonFilteredFileExtension>jsp</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
        <webResources>
            <resource>
                <directory>src/main/webapp/</directory>
                <targetPath>WEB-INF</targetPath>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </webResources>
        <warName>Application</warName>
    </configuration>
</plugin>

war 파일은 단순히 war 확장자가있는 jar 파일이지만 내용이 실제로 구조화되는 방식이 작동합니다.

J2EE / Java EE 튜토리얼은 시작이 될 수 있습니다.

http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/WebComponents3.html

And the Servlet specification contains the gory details:

http://java.sun.com/products/servlet/download.html

If you create a new web project in Eclipse (I am referring to the Java EE version), the structure is created for you and you can also tell it where your Appserver is installed and it will deploy and start the application for you.

Using the "Export->WAR file" option will let you save the war file.


If you are not sure what to do and are starting from scratch then Maven can help get you started.

By following the the below steps you can get a new war project setup perfectly in eclipse.

  1. Download and install Maven
  2. Go the command line run: mvn archetype:generate
  3. Follow the prompted steps - choosing the simple java web project (18) and a suitable name.
  4. When it is finished run: mvn eclipse:eclipse
  5. Start Eclipse. Choose File -> Import -> Existing project. Select the directory where you ran the mvn goals.
  6. That's it you should now have a very good start to a war project in eclipse
  7. You can create the war itself by running mvn package or deploy it by setting up a server in eclipse and simply adding adding the project to the server.

As some others have said the downside of using maven is that you have to use the maven conventions. But I think if you are just starting out, learning the conventions is a good idea before you start making your own. There's nothing to stop you changing/refactoring to your own preferred method at a later point.

Hope this helps.


Use the Ant war task


Use ant build code I use this for my project SMS

<property name="WEB-INF" value="${basedir}/WebRoot/WEB-INF" />
<property name="OUT" value="${basedir}/out" />
<property name="WAR_FILE_NAME" value="mywebapplication.war" />
<property name="TEMP" value="${basedir}/temp" />

<target name="help">
    <echo>
        --------------------------------------------------
        compile - Compile
        archive - Generate WAR file
        --------------------------------------------------
    </echo>
</target>

<target name="init">
    <delete dir="${WEB-INF}/classes" />
    <mkdir dir="${WEB-INF}/classes" />
</target>

<target name="compile" depends="init">
    <javac srcdir="${basedir}/src" 
                destdir="${WEB-INF}/classes" 
                classpathref="libs">
    </javac>
</target>

<target name="archive" depends="compile">
    <delete dir="${OUT}" />
    <mkdir dir="${OUT}" />
    <delete dir="${TEMP}" />
    <mkdir dir="${TEMP}" />
    <copy todir="${TEMP}" >
        <fileset dir="${basedir}/WebRoot">
        </fileset>
    </copy>
    <move file="${TEMP}/log4j.properties" 
                    todir="${TEMP}/WEB-INF/classes" />
    <war destfile="${OUT}/${WAR_FILE_NAME}" 
                    basedir="${TEMP}" 
                    compress="true" 
                    webxml="${TEMP}/WEB-INF/web.xml" />
    <delete dir="${TEMP}" />
</target>

<path id="libs">
    <fileset includes="*.jar" dir="${WEB-INF}/lib" />
</path>


Another option would be to build it automatically using Eclipse. Of course if you have continuous integration environment Ant or Maven is recommended. The export alternative is not very convenient because you have to configure every time the export properties.

STEPS:

  1. Enable "Project Archives" support; this might depend on your project (I used it on Java EE/Web project). Right-click project root directory; Configure -> Add Project Archives Support.

  2. Go and create a new archive in the "Project Archives" top dir. You have only jar option, but name you archive *.war.

  3. Configure Fileset-s, i.e what files to be included. Typical is to configure two filesets similar how the Web Deployment Assembly (project property) is configured.

    • copy /WebContent to /
    • copy /build/classes to WEB-INF/classes (create this fileset after you define the WEB-INF/classes directory in the archive)
  4. You might need to tweek the fileset exclude property depending where you placed some of the config files or you might need more filesets, but the idea is that once you configured this you don't need to change it.

  5. Build the archive manually or publish directly to server; but is also automatically built for you by Eclipse


Another common option is gradle.

http://www.gradle.org/docs/current/userguide/application_plugin.html

To build your war file in a web app:

In build.gradle, add:

apply plugin: 'war'

Then:

./gradlew war

Use the layout from accepted answer above.


Use this command outside the WEB-INF folder. This should create your war file. This is a quickest method I know.

You will need JDK 1.7+ installed to achieve this feat and environment variables that point to the bin directory of your JDK.

jar -cvf projectname.war *

Reference Link


Simpler solution which also refreshes the Eclipse workspace:

<?xml version="1.0" encoding="UTF-8"?>
<project name="project" default="default">    
    <target name="default">
        <war destfile="target/MyApplication.war" webxml="web/WEB-INF/web.xml">
            <fileset dir="src/main/java" />
            <fileset dir="web/WEB-INF/views" />
            <lib dir="web/WEB-INF/lib"/>
            <classes dir="target/classes" />
        </war>
        <eclipse.refreshLocal resource="MyApplication/target" depth="infinite"/>
    </target>
</project>

Simplistic Shell code for creating WAR files from a standard Eclipse dynamic Web Project. Uses RAM File system (/dev/shm) on a Linux platform.

#!/bin/sh

UTILITY=$(basename $0)

if [ -z "$1" ] ; then
    echo "usage: $UTILITY [-s] <web-app-directory>..."
    echo "       -s ..... With source"
    exit 1
fi

if [ "$1" == "-s" ] ; then
    WITH_SOURCE=1
    shift
fi

while [ ! -z "$1" ] ; do
    WEB_APP_DIR=$1

    shift

    if [ ! -d $WEB_APP_DIR ] ; then
        echo "\"$WEB_APP_DIR\" is not a directory"
        continue
    fi

    if [ ! -d $WEB_APP_DIR/WebContent ] ; then
        echo "\"$WEB_APP_DIR\" is not a Web Application directory"
        continue
    fi

    TMP_DIR=/dev/shm/${WEB_APP_DIR}.$$.tmp
    WAR_FILE=/dev/shm/${WEB_APP_DIR}.war

    mkdir $TMP_DIR

    pushd $WEB_APP_DIR > /dev/null
    cp -r WebContent/* $TMP_DIR
    cp -r build/* $TMP_DIR/WEB-INF
    [ ! -z "$WITH_SOURCE" ] && cp -r src/* $TMP_DIR/WEB-INF/classes
    cd $TMP_DIR > /dev/null
    [ -e $WAR_FILE ] && rm -f $WAR_FILE
    jar cf $WAR_FILE .
    ls -lsF $WAR_FILE
    popd > /dev/null

    rm -rf $TMP_DIR
done

**Making War file in Eclips Gaynemed of grails web project **

1.Import project:

2.Change the datasource.groovy file

Like this: url="jdbc:postgresql://18.247.120.101:8432/PGMS"

2.chnge AppConfig.xml

3.kill the Java from Task Manager:

  1. run clean comand in eclips

  2. run 'prod war' fowllowed by project name.

  3. Check the log file and find the same .war file in directory of workbench with same date.

참고URL : https://stackoverflow.com/questions/1001714/how-to-create-war-files

반응형