Está usted en Indice > Maletin > Artículos > Desplegar Servlets y Aplicaciones Web en Tomcat y WebLogic Server
Construcción
Maletín
Utilidades
Cursos
Promoción
Rentabilidad
Zona Novatos
Foros
Acceso a tu cuenta

Desplegar Servlets y Aplicaciones Web en Tomcat y WebLogic Server (2)

Para sumarizar, cuando escribamos nuestros servlets HTTP, deberíamos:

1. Importar como mínimo las clases servlets:
* javax.servlet.ServletException
* javax.servlet.http.HttpServlet
* javax.servlet.http.HttpServletRequest
* javax.servlet.http.HttpServletResponse
2. Hacer la clase public
3. Hacer que la clase extienda HttpServlet
4. Sobreescribir los métodos doXXX() apropiados para implementar nuestra lógica de solicitud/respuesta..

Un Servlet de Ejemplo: RequestDetails

En el ejemplo de abajo hemos ilustrado un simple servlet HTTP. La primera línea simplemente define a qué paquete pertenece el servlet. El siguiente bloque de código importa las clases usadas en este servlet. Luego viene la definición de la clase servlet. Como puedes ver, la clase RequestDetails extiende HttpServlet.

El cuerpo de RequestDetails define dos métodos: doGet() y doPost(). El método doGet() define la funcionalidad principal de este servlet. El método doPost()simplemente llama a doGet(). Por lo tanto, el servlet maneja las peticiones GET y POST de la misma forma.

El método doGet() construye una página HTML que contiene detalles sobre la solicitud HTTP enviada al servidor. Observa las dos primeras líneas del método. La primera línea selecciona el tipo de contenido de la respuesta. En general, construiremos una página HTML, en cuyo caso el tipo de contenido debe configurarse como text/html. La segunda línea del método doGet() obtiene una referencia a un stream de salida PrintWriter. Toda la salida a devolver para el cliente se escribe en este stream de salida:

package org.stevengould.javaworld;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* This class provides a simple example of a servlet, and
* illustrates some of the information available from an
* HTTP request.
*/
public class RequestDetails extends HttpServlet {
/**
* Handler for all GET requests. We simply dump out the
* requestheader information, followed by the body of
* the request.
* @param request the HTTP request submitted to the
* server for processing. It is this object that
* contains the details of the requested URL, and
* it is the details of this object that we
* output as a response.
* @param response the response object to be used to
* send a result back to the client.
* @exception IOException thrown if a communications
* error occurs.
*@exception ServletException if the GET request could
* could not be handled
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Request Details Example</title>");
out.println("</head>");
out.println("<body>");

out.println("<h3>HTTP Request Header</h3>");
out.println("<table border='1'>");
out.println(" <tr bgcolor=#e0e0e0>");
out.println(" <td><strong>Name</strong></td>");
out.println(" <td><strong>Value</strong></td>");
out.println(" </tr>");
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = request.getHeader(name);
out.println(" <tr>");
out.println(" <td bgcolor=#e0e0e0>"+name+"</td>");
out.println(" <td>"+value+"</td>");
out.println(" </tr>");
}
out.println("</table>");

out.println("<h3>HTTP Request Information</h3>");
out.println("<table border='1'>");
out.println(" <tr bgcolor=#e0e0e0>");
out.println(" <td><strong>Name</strong></td>");
out.println(" <td><strong>Value</strong></td>");
out.println(" </tr>");
out.println(" <tr>");
out.println(" <td bgcolor=#e0e0e0>Method:</td>");
out.println(" <td>"+request.getMethod()+"</td>");
out.println(" </tr>");
out.println(" <tr>");
out.println(" <td bgcolor=#e0e0e0>Request URI:</td>");
out.println(" <td>"+request.getRequestURI()+"</td>");
out.println(" </tr>");
out.println(" <tr>");
out.println(" <td bgcolor=#e0e0e0>Protocol:</td>");
out.println(" <td>"+request.getProtocol()+"</td>");
out.println(" </tr>");
out.println(" <tr>");
out.println(" <td bgcolor=#e0e0e0>PathInfo:</td>");
out.println(" <td>"+request.getPathInfo()+"</td>");
out.println(" </tr>");
out.println(" <tr>");
out.println(" <td bgcolor=#e0e0e0>Remote Address:</td>");
out.println(" <td>"+request.getRemoteAddr()+"</td>");
out.println(" </tr>");
out.println("</table>");

out.println("<hr>");
Date date = new Date();
out.println("<p align=center>Page generated on "+date);

out.println("</body>");
out.println("</html>");

out.close();
}

/**
* For POST requests, we will simply perform the same
*operations as for GET requests. The best way to do this
* is to simply invoke the doGet() method with the appropriate
* parameters.
* @param request the HTTP request submitted to the server
* for processing. It is this object that contains
* the details of the requested URL, and it is the
* details of this object that we output as a
* response.
* @param response the response object to be used to send a
* result back to the client.
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
}



Usuarios que han visto este tema también han visto...

- Guía Breve de Seguridad
- Cómo analiza Google los enlaces
- Ideas para conseguir enlaces
- Cuanto dinero quieres ganar este año?
- Elige. Tu dominio con o sin www


Versión imprimible - Versión imprimible de este documento
Enviar e-mail - Enviar por e-mail este documento
Publicidad

Información legal | Política de Privacidad | Contacte con nosotros

Otro proyecto de Factoría de Internet. Copyright© 2003-2008 Factoría de Internet S.L.. Todos los derechos reservados.


Página generada el 22-11-2008 a las 14:38:42