Instalar Eclipse
- descargar eclipse de http://www.eclipse.org
- Descomprimir Eclipse en el disco duro y arrancar aplicación
- configurar el ambiente de trabajo especificando el directorio de trabajo
Instalar TomCat
- Descargar Tomcat de http://tomcat.apache.org/
- dependiendo de la versión descargada instalarla o copiar y pegar en la ruta adecuada
- verificar su funcionamiento abriendo el localhost:8080 o el puerto que se haya especificado
Crear un proyecto nuevo
- Seleccionar File-new-project
- en la primer ventana seleccionar java project
- en la segunda ventana especificar el nombre del proyecto (dar HelloWebApp)
- finalizar
HelloWebApp (el proyecto)
--src
----com.hello (este es un paquete no una carpeta)
--lib
--web
----WEB-INF
--src
----com.hello (este es un paquete no una carpeta)
--lib
--web
----WEB-INF
la carpeta src contiene los archivos java fuente, incluyendo las clases Servlet que incluye el paquete com.hello.
la carpeta lib contiene los jars de los que depende el proyecto.
la carpeta web contiene los archivos jsp, html, javascript y css, tembien contiene el archivo WEB_INF que contiene a su vez el archivo web.xml del proyecto
asi es como deberá verse el proyecto
Copiar librería servlet-api.jar a directorio lib del proyecto
- junto con el paquete de instlaacion de tomcat en la carpeta lib se encuentra este archivo, simplemente hay que copiar y pegar en la carpeta lib del proyecto, se desplegara una ventana en donde se selecciona copiar
- una vez copiado se hace click derecho sobre la libreria y se selecciona build-path y luego add to build path
- el icono cambiara a uno como el de las demás librerías
Crear un Servlet
- click derecho sobre com.hello (paquete) en el folder src, seleccionar new -> class
- ponerle por nombre HelloServlet
- copiar en este archivo el siguiente codigo
- package com.hello;
- import java.io.IOException;
- import javax.servlet.Servlet;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class HelloServlet extends HttpServlet implements Servlet {
- private static final long serialVersionUID = 1L;
- public HelloServlet() {
- super();
- }
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- request.setAttribute("hello_string", "Hello WebApp!");
- request.getRequestDispatcher("/hello.jsp").forward(request, response);
- }
- }
Crear un archivo JSP
- click derecho sobre el folder web y seleccionar New -> Other, se abrirá un asistente, se debera seleccionar JSP file type que esta en el folder Web, nombrar a este como hello.jps
- copiar y pegar el siguiente codigo
- <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
- pageEncoding="ISO-8859-1"%>
- <!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=ISO-8859-1">
- <title>Hello Web App</title>
- </head>
- <body>
- <h3><%=(String)request.getAttribute("hello_string")%></h3>
- </body>
- </html>
De la misma forma crear otro archivo jsp y nombrarlo index.jsp, copiar y pegar lo siguiente
- <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
- pageEncoding="ISO-8859-1"%>
- <!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=ISO-8859-1">
- <title>Index</title>
- </head>
- <body>
- <jsp:forward page="/hello" />
- </body>
- </html>
Crear un archivo XML
- Click derecho en el folder WEB_INF y seleccionar New -> File. nombrar como web.xml
- copiar y pegar el código siguiente
- <?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
- <display-name>HelloWebApp</display-name>
- <servlet>
- <servlet-name>HelloServlet</servlet-name>
- <servlet-class>com.hello.HelloServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>HelloServlet</servlet-name>
- <url-pattern>/hello</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
crear otro archivo xml al mismo nivel y llamarlo build.xml, copiar y pegar el codigo
view plainprint?
crear un archivo properties. click derecho sobre el archivo de proyecto HelloWebApp, seleccionar New->File y nombrar este como build.properties, copiar y pegar el siguiente codigo
Asi es como debe verse la estructura del proyecto en el Package Explorer View de Eclipse

- <?xml version="1.0"?>
- <project name="hello" default="deploy_local" basedir=".">
- <property file="build.properties"/>
- <path id="classpath">
- <fileset dir="${lib.dir}" includes="servlet-api.jar"/>
- </path>
- <target name="clean">
- <echo>Cleaning the ${build.dir}</echo>
- <delete dir="${build.dir}"/>
- <delete dir="${dist.dir}"/>
- </target>
- <target name="init" depends="clean">
- <echo>Creating the build directory</echo>
- <mkdir dir="${build.dir}/WEB-INF/classes"/>
- <mkdir dir="${build.dir}/WEB-INF/lib"/>
- <mkdir dir="${dist.dir}"/>
- </target>
- <target name="compile" depends="init">
- <echo>Compile the source files</echo>
- <javac srcdir="${src.dir}" destdir="${build.dir}/WEB-INF/classes">
- <classpath refid="classpath"/>
- </javac>
- </target>
- <target name="copy" depends="compile">
- <copy todir="${build.dir}/WEB-INF">
- <fileset dir="${web.dir}/WEB-INF"/>
- </copy>
- <copy todir="${build.dir}">
- <fileset dir="${web.dir}"/>
- </copy>
- <copy todir="${build.dir}/WEB-INF/lib">
- <fileset dir="${lib.dir}">
- <exclude name="servlet-api.jar"/>
- </fileset>
- </copy>
- </target>
- <target name="war" depends="copy">
- <echo>Building the war file</echo>
- <war destfile="${dist.dir}/${project.name}.war" webxml="${build.dir}/WEB-INF/web.xml">
- <fileset dir="${build.dir}"/>
- </war>
- </target>
- <target name="deploy_local" depends="war">
- <echo>Deploying .war to local Tomcat</echo>
- <copy todir="${tomcat.dir}">
- <fileset dir="${dist.dir}">
- <include name="${project.name}.war"/>
- </fileset>
- </copy>
- </target>
- </project>
crear un archivo properties. click derecho sobre el archivo de proyecto HelloWebApp, seleccionar New->File y nombrar este como build.properties, copiar y pegar el siguiente codigo
- project.name=HelloWebApp
- lib.dir=lib
- src.dir=src
- web.dir=web
- build.dir=build
- dist.dir=dist
- tomcat.dir=/Library/Tomcat/webapps
Asi es como debe verse la estructura del proyecto en el Package Explorer View de Eclipse

Entendiendo el archivo build.xml
Tenemos un proyecto Java Web llamada Hello World en Eclipse llamado HelloWebApp que contiene un archivo build.xml que se muestra a continuacion. El archivo build es usado por ANT para tomar el codigo fuente y archivos de configuracion del proyecto, compilarlos y empaquetarlos en un archivo .war que es usado por Tomcat para ejecutar la aplicacion.
Archivo build.xml
archivo build.properties
view plainprint?
El archivo build consiste de muchas etiquetas target y un archivo properties y definiciones de clases. El ANT builder, que viene embebido en eclipse, traduce el archivo y convierte las instrucciones definidas en el. A continuacion iremos paso a paso explicando que es lo que hace el constructor de ANT
Linea 2: El "deploy_local" target es el blanco final y será implementado primero. El "basedir", es a donde todos los paths seran relativos es definido como "." con lo que se refiere al directorio donde reside el archivo build.xml.
Linea 4: El archiv "build.properties" es importado por ANT y almacena ciertos valores de llaves usados por el build. Generalmente los nombres de directorios y paths son definidos en el archivo porperties.
Line 6: The jars in the classpath are used by ANT when compiling the Java source code.
Line 51: Let's skip down to this line because ANT starts with this target because it is defined as the default target. This target depends on the "war" target, which depends on the "copy" target, which depends on the "compile" target, which depends on the "init" target, which depends on the "clean" target. So actually, this means the "clean" target will be implemented first, then the "init" and so on...
Line 10: The "echo" element just prints out to the console what you tell it to. In this case, "Cleaning the ${build.dir}", where "${build.dir}" is replaced with the value "build" from the build.properties file, and "Cleaning the build" is printed out. The "delete" elements delete the "build" and "dist" folders in the project if they exist.
Line 16: The "init" target creates 3 folders in the project: "build/WEB-INF/classes", "build/WEB-INF/lib", and "dist".
Line 23: The "compile" target compiles all the java files found in the src folder and puts them in the "build/WEB-INF/classes" folder. It uses the jars defined on the classpath on line 6.
Line 30: The "copy" target moves files from the "web" and "lib" folders to the "build" folder.
Line 39: We don't copy over the servlet-api.jar because the Tomcat server already contains this jar. After all, that we're the jar came from in the first place.
Line 44: The "war" target takes everything in the "build folder", makes a WAR file and puts it in the "dist" folder.
Line 53: Inside the "deploy_local" target, the war is copied from the "dist" folder to the "/Library/Tomcat/webapps" folder, which is where the Tomcat installation resides.
Step 2: Run ANT to build the project. Right-click on build.xml and choose Run As --> Ant Build.

Here's what your new HelloWebApp Java project should now look like in the Eclipse Package Explorer View after the ANT build:

Step 3: Startup Tomcat. Now that the Tomcat installation has the WAR file in it's webapps folder, you need to start Tomcat up so it runs the web app. To do this, fire up the terminal and type: "sh /Library/Tomcat/bin/startup.sh". If you're using a non-UNIX-based computer (Windows), you have to start the startup.bat file instead, remove the sh at the front of the command, and adjust your path appropriately.
Step 4: Check out your web application in action. Point your browser to http://127.0.0.1:8080/HelloWebApp/ . You should see the Hello Web App web application in it's full glory!

Tenemos un proyecto Java Web llamada Hello World en Eclipse llamado HelloWebApp que contiene un archivo build.xml que se muestra a continuacion. El archivo build es usado por ANT para tomar el codigo fuente y archivos de configuracion del proyecto, compilarlos y empaquetarlos en un archivo .war que es usado por Tomcat para ejecutar la aplicacion.
Archivo build.xml
- <?xml version="1.0"?>
- <project name="hello" default="deploy_local" basedir=".">
- <property file="build.properties"/>
- <path id="classpath">
- <fileset dir="${lib.dir}" includes="servlet-api.jar"/>
- </path>
- <target name="clean">
- <echo>Cleaning the ${build.dir}</echo>
- <delete dir="${build.dir}"/>
- <delete dir="${dist.dir}"/>
- </target>
- <target name="init" depends="clean">
- <echo>Creating the build directory</echo>
- <mkdir dir="${build.dir}/WEB-INF/classes"/>
- <mkdir dir="${build.dir}/WEB-INF/lib"/>
- <mkdir dir="${dist.dir}"/>
- </target>
- <target name="compile" depends="init">
- <echo>Compile the source files</echo>
- <javac srcdir="${src.dir}" destdir="${build.dir}/WEB-INF/classes">
- <classpath refid="classpath"/>
- </javac>
- </target>
- <target name="copy" depends="compile">
- <copy todir="${build.dir}/WEB-INF">
- <fileset dir="${web.dir}/WEB-INF"/>
- </copy>
- <copy todir="${build.dir}">
- <fileset dir="${web.dir}"/>
- </copy>
- <copy todir="${build.dir}/WEB-INF/lib">
- <fileset dir="${lib.dir}">
- <exclude name="servlet-api.jar"/>
- </fileset>
- </copy>
- </target>
- <target name="war" depends="copy">
- <echo>Building the war file</echo>
- <war destfile="${dist.dir}/${project.name}.war" webxml="${build.dir}/WEB-INF/web.xml">
- <fileset dir="${build.dir}"/>
- </war>
- </target>
- <target name="deploy_local" depends="war">
- <echo>Deploying .war to local Tomcat</echo>
- <copy todir="${tomcat.dir}">
- <fileset dir="${dist.dir}">
- <include name="${project.name}.war"/>
- </fileset>
- </copy>
- </target>
- </project>
view plainprint?
- project.name=HelloWebApp
- lib.dir=lib
- src.dir=src
- web.dir=web
- build.dir=build
- dist.dir=dist
- tomcat.dir=/Library/Tomcat/webapps
El archivo build consiste de muchas etiquetas target y un archivo properties y definiciones de clases. El ANT builder, que viene embebido en eclipse, traduce el archivo y convierte las instrucciones definidas en el. A continuacion iremos paso a paso explicando que es lo que hace el constructor de ANT
Linea 2: El "deploy_local" target es el blanco final y será implementado primero. El "basedir", es a donde todos los paths seran relativos es definido como "." con lo que se refiere al directorio donde reside el archivo build.xml.
Linea 4: El archiv "build.properties" es importado por ANT y almacena ciertos valores de llaves usados por el build. Generalmente los nombres de directorios y paths son definidos en el archivo porperties.
Line 6: The jars in the classpath are used by ANT when compiling the Java source code.
Line 51: Let's skip down to this line because ANT starts with this target because it is defined as the default target. This target depends on the "war" target, which depends on the "copy" target, which depends on the "compile" target, which depends on the "init" target, which depends on the "clean" target. So actually, this means the "clean" target will be implemented first, then the "init" and so on...
Line 10: The "echo" element just prints out to the console what you tell it to. In this case, "Cleaning the ${build.dir}", where "${build.dir}" is replaced with the value "build" from the build.properties file, and "Cleaning the build" is printed out. The "delete" elements delete the "build" and "dist" folders in the project if they exist.
Line 16: The "init" target creates 3 folders in the project: "build/WEB-INF/classes", "build/WEB-INF/lib", and "dist".
Line 23: The "compile" target compiles all the java files found in the src folder and puts them in the "build/WEB-INF/classes" folder. It uses the jars defined on the classpath on line 6.
Line 30: The "copy" target moves files from the "web" and "lib" folders to the "build" folder.
Line 39: We don't copy over the servlet-api.jar because the Tomcat server already contains this jar. After all, that we're the jar came from in the first place.
Line 44: The "war" target takes everything in the "build folder", makes a WAR file and puts it in the "dist" folder.
Line 53: Inside the "deploy_local" target, the war is copied from the "dist" folder to the "/Library/Tomcat/webapps" folder, which is where the Tomcat installation resides.
Step 2: Run ANT to build the project. Right-click on build.xml and choose Run As --> Ant Build.

Here's what your new HelloWebApp Java project should now look like in the Eclipse Package Explorer View after the ANT build:

Step 3: Startup Tomcat. Now that the Tomcat installation has the WAR file in it's webapps folder, you need to start Tomcat up so it runs the web app. To do this, fire up the terminal and type: "sh /Library/Tomcat/bin/startup.sh". If you're using a non-UNIX-based computer (Windows), you have to start the startup.bat file instead, remove the sh at the front of the command, and adjust your path appropriately.
Step 4: Check out your web application in action. Point your browser to http://127.0.0.1:8080/HelloWebApp/ . You should see the Hello Web App web application in it's full glory!

Exelente, ahora si entiendo como funciona por dentro eclipse
ResponderEliminar