Ir al contenido principal

Hola Mundo Java Web con Eclipse

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
Crear la siguiente estructura de carpetas en el proyecto
HelloWebApp (el proyecto)
--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
  1. package com.hello;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.Servlet;  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. public class HelloServlet extends HttpServlet implements Servlet {  
  12.   
  13. private static final long serialVersionUID = 1L;  
  14.   
  15. public HelloServlet() {  
  16. super();  
  17. }  
  18.   
  19. @Override  
  20. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  21.   
  22. request.setAttribute("hello_string""Hello WebApp!");  
  23.   
  24. request.getRequestDispatcher("/hello.jsp").forward(request, response);  
  25.   
  26. }  

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
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2. pageEncoding="ISO-8859-1"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  7. <title>Hello Web App</title>  
  8. </head>  
  9. <body>  
  10. <h3><%=(String)request.getAttribute("hello_string")%></h3>  
  11. </body>  
  12. </html>  

De la misma forma crear otro archivo jsp y nombrarlo index.jsp, copiar y pegar lo siguiente
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2. pageEncoding="ISO-8859-1"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  7. <title>Index</title>  
  8. </head>  
  9. <body>  
  10. <jsp:forward page="/hello" />  
  11. </body>  
  12. </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

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <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">  
  3.   
  4. <display-name>HelloWebApp</display-name>  
  5.   
  6. <servlet>  
  7. <servlet-name>HelloServlet</servlet-name>  
  8. <servlet-class>com.hello.HelloServlet</servlet-class>  
  9. </servlet>  
  10.   
  11. <servlet-mapping>  
  12. <servlet-name>HelloServlet</servlet-name>  
  13. <url-pattern>/hello</url-pattern>  
  14. </servlet-mapping>  
  15.   
  16. <welcome-file-list>  
  17. <welcome-file>index.jsp</welcome-file>  
  18. </welcome-file-list>  
  19.   
  20. </web-app>  
crear otro archivo xml al mismo nivel y llamarlo build.xml, copiar y pegar el codigo
view plainprint?
  1. <?xml version="1.0"?>  
  2. <project name="hello" default="deploy_local" basedir=".">  
  3.   
  4. <property file="build.properties"/>  
  5.   
  6. <path id="classpath">  
  7. <fileset dir="${lib.dir}" includes="servlet-api.jar"/>  
  8. </path>  
  9.   
  10. <target name="clean">  
  11. <echo>Cleaning the ${build.dir}</echo>  
  12. <delete dir="${build.dir}"/>  
  13. <delete dir="${dist.dir}"/>  
  14. </target>  
  15.   
  16. <target name="init" depends="clean">  
  17. <echo>Creating the build directory</echo>  
  18. <mkdir dir="${build.dir}/WEB-INF/classes"/>  
  19. <mkdir dir="${build.dir}/WEB-INF/lib"/>  
  20. <mkdir dir="${dist.dir}"/>  
  21. </target>  
  22.   
  23. <target name="compile" depends="init">  
  24. <echo>Compile the source files</echo>  
  25. <javac srcdir="${src.dir}" destdir="${build.dir}/WEB-INF/classes">  
  26. <classpath refid="classpath"/>  
  27. </javac>  
  28. </target>  
  29.   
  30. <target name="copy" depends="compile">  
  31. <copy todir="${build.dir}/WEB-INF">  
  32. <fileset dir="${web.dir}/WEB-INF"/>  
  33. </copy>  
  34. <copy todir="${build.dir}">  
  35. <fileset dir="${web.dir}"/>  
  36. </copy>  
  37. <copy todir="${build.dir}/WEB-INF/lib">  
  38. <fileset dir="${lib.dir}">  
  39. <exclude name="servlet-api.jar"/>  
  40. </fileset>  
  41. </copy>  
  42. </target>  
  43.   
  44. <target name="war" depends="copy">  
  45. <echo>Building the war file</echo>  
  46. <war destfile="${dist.dir}/${project.name}.war" webxml="${build.dir}/WEB-INF/web.xml">  
  47. <fileset dir="${build.dir}"/>  
  48. </war>  
  49. </target>  
  50.   
  51. <target name="deploy_local" depends="war">  
  52. <echo>Deploying .war to local Tomcat</echo>  
  53. <copy todir="${tomcat.dir}">  
  54. <fileset dir="${dist.dir}">  
  55. <include name="${project.name}.war"/>  
  56. </fileset>  
  57. </copy>  
  58. </target>  
  59.   
  60. </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
  1. project.name=HelloWebApp  
  2. lib.dir=lib  
  3. src.dir=src  
  4. web.dir=web  
  5. build.dir=build  
  6. dist.dir=dist  
  7. 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

  1. <?xml version="1.0"?>  
  2. <project name="hello" default="deploy_local" basedir=".">  
  3.   
  4. <property file="build.properties"/>  
  5.   
  6. <path id="classpath">  
  7. <fileset dir="${lib.dir}" includes="servlet-api.jar"/>  
  8. </path>  
  9.   
  10. <target name="clean">  
  11. <echo>Cleaning the ${build.dir}</echo>  
  12. <delete dir="${build.dir}"/>  
  13. <delete dir="${dist.dir}"/>  
  14. </target>  
  15.   
  16. <target name="init" depends="clean">  
  17. <echo>Creating the build directory</echo>  
  18. <mkdir dir="${build.dir}/WEB-INF/classes"/>  
  19. <mkdir dir="${build.dir}/WEB-INF/lib"/>  
  20. <mkdir dir="${dist.dir}"/>  
  21. </target>  
  22.   
  23. <target name="compile" depends="init">  
  24. <echo>Compile the source files</echo>  
  25. <javac srcdir="${src.dir}" destdir="${build.dir}/WEB-INF/classes">  
  26. <classpath refid="classpath"/>  
  27. </javac>  
  28. </target>  
  29.   
  30. <target name="copy" depends="compile">  
  31. <copy todir="${build.dir}/WEB-INF">  
  32. <fileset dir="${web.dir}/WEB-INF"/>  
  33. </copy>  
  34. <copy todir="${build.dir}">  
  35. <fileset dir="${web.dir}"/>  
  36. </copy>  
  37. <copy todir="${build.dir}/WEB-INF/lib">  
  38. <fileset dir="${lib.dir}">  
  39. <exclude name="servlet-api.jar"/>  
  40. </fileset>  
  41. </copy>  
  42. </target>  
  43.   
  44. <target name="war" depends="copy">  
  45. <echo>Building the war file</echo>  
  46. <war destfile="${dist.dir}/${project.name}.war" webxml="${build.dir}/WEB-INF/web.xml">  
  47. <fileset dir="${build.dir}"/>  
  48. </war>  
  49. </target>  
  50.   
  51. <target name="deploy_local" depends="war">  
  52. <echo>Deploying .war to local Tomcat</echo>  
  53. <copy todir="${tomcat.dir}">  
  54. <fileset dir="${dist.dir}">  
  55. <include name="${project.name}.war"/>  
  56. </fileset>  
  57. </copy>  
  58. </target>  
  59.   
  60. </project>  
archivo build.properties
view plainprint?
  1. project.name=HelloWebApp  
  2. lib.dir=lib  
  3. src.dir=src  
  4. web.dir=web  
  5. build.dir=build  
  6. dist.dir=dist  
  7. 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!





Comentarios

Publicar un comentario

Entradas populares de este blog

Email directly from 4GL - V9.1/3.1 only

/*------------------------------------------------------------------- File........: smtpmail.p Version.....: 5.8c - Feb 25, 2009 Description : Opens up an SMTP connection and sends an email message to multiple recipients. Input Param : mailhub char - settable SMTP server name/IP address optionally append :XX where X is a port number of the SMTP server. 25 is default port. EmailTo CHAR - list of email addresses separated by semicolons or commas (All semicolons will be replaced by commas so don't include stuff like Smith, John) <me@myaddress.org>"My Name" EmailFrom CHAR - email address of user originating the email, the SMTP server should require that this user is real. Format looks like: <user>@<host>[;<descriptive name>][^replytouser>@<replytohost] ...

Progress Explorer Tool en Windows Server 2008

Al intentar abrir el Progress Explorer Tool en Windows 2008 Server este regresa un mensaje  este es un post en ingles ubicado en  http://alasdaircs.wordpress.com/2011/02/17/progress-explorer-and-windows-2008/ gracias a alasdairc por compartirlo Para solucionar el problema basta con modificar el registro a los valores mostrados a continuacion. [HKEY_CURRENT_USER\Software\Microsoft\Java VM] “EnableLogging”=hex:00,00,00,00 “EnableJIT”=hex:00,00,00,00 [HKEY_USERS\.Default\Software\Microsoft\Java VM] “EnableLogging”=hex:00,00,00,00 “EnableJIT”=hex:00,00,00,00

Editar PL files

Los archivos .pl en progress son progress library pueden contener tanto codigo fuente como programas compilados. En la siguiente ruta pueden localizar una herramienta para examinar el contenido de estos archivos. http://progress-tools.x10.mx/winpl.html Winpl