SlideShare a Scribd company logo
1 of 118
Download to read offline
Servlet
(Fundamentos)
       )        1
Tópicos

    Servlet – la gran figura de J2EE

    Servlet - modelo request & response

    Servlet – ciclo de vida

    Servlet – alcance de los objetos

    Servlet request

    Servlet response: Status, Header, Body

    Tratamiento de errores


                                             2
Tópicos avanzados:

    Session Tracking

    Servlet Filters

    Eventos del ciclo de vida del servlet

    Including, forwarding to, y redirect a otros
    recursos de la web

    Tratamiento de la concurrencia

    Invoker Servlet

                                               3
Servlet
La gran figura de J2EE

                    4
Arquitectura J2EE 1.2
An extensible Web technology that uses template data,   Java Servlet A Java program that
custom elements, scripting languages, and server-side   extends the functionality of a Web
Java objects to return dynamic content to a client .    server, generating dynamic content
Typically the template data is HTML or XML elements.    and interacting with Web clients
The client is often a Web browser.                      using a request-response
                                                        paradigm .




                                                                                             5
¿Dónde estan los Servlets y JSP?




              Web Tier   EJB Tier




                                    6
¿Qué es un Servlet?

    Objetos Java™ objects que estan basados
    en un marco de trabajo y APIs los cuales
    extienden la funcionalidad de un servidor
    HTTP.

    Mapeado a un URL y manejado por el
    contenedor con una arquitectura simple

    Disponible y ejecutable en la gran mayoria
    de servidores web y servidores de
    aplicaciones

    Independiente de la plataforma y servidor
                                                 7
Primer código Servlet
Public class HelloServlet extends HttpServlet {

  public void doGet(HttpServletRequest request,
                     HttpServletResponse
response){
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<title>Hello World!</title>");
  }
  ...
}



                                              8
Servlet


         CGI                          Servlet

    Escrito en C, C++,        
                                  Escrito en Java
    Visual Basic y Perl       
                                  Poderoso y eficiente

    Dificil de mantener, no   
                                  Promueve la
    es escalable, no es           escalabilidad,
    administrable                 reusabilidad (basado en

    Problemas de                  componentes)
    seguridad                 
                                  Construido bajo la

    Ineficiente uso de            seguridad del lenguaje
    recursos                      java

    Especifico a la           
                                  Independiente de la
    plataforma y aplicación       plataforma y portable


                                                            9
Servlet vs. CGI
Request CGI1
Request CGI1                       Child for CGI1
                                   Child for CGI1
Request CGI2         CGI
                      CGI
Request CGI2        Based          Child for CGI2
                     Based         Child for CGI2
                   Webserver
                   Webserver
Request CGI1
Request CGI1                       Child for CGI1
                                   Child for CGI1

Request Servlet1
Request Servlet1       Servlet Based Webserver
                       Servlet Based Webserver
Request Servlet2                       Servlet1
                                       Servlet1
Request Servlet2
                     JVM
                     JVM
Request Servlet1                       Servlet2
                                       Servlet2


                                                    10
Ventajas de los Servlet

    No tiene las limitaciones de los CGI

    Muchas herramientas y servidores Web en el
    mercado soportan Servlet

    Acceso a la familia entera de APIs Java

    Confiable, mejor performance y escalabilidad

    Independiente de la plataforma y servidor

    Seguro

    Muchos servidores permitir un refresco automatico
    de servlets por accion administrativa


                                                        11
¿Qué es la tecnología JSP?

    Permite la separación de lógica de
    negocio y la presentación
    −   La presentacion es generalmente en la
        forma de HTML o XML/XSLT
    −   La logica de negocios es implementada
        como Java Beans o custom tags
    −   Mejor mantenimiento, reusabilidad

    Extensible via custom tags

    Construido en base a la tecnologia de
    servlets
                                                12
¿Qué es una pagina JSP?

    Un documento basado en texto
    capaza de retornar contenido
    dinamico a un browser

    Contiene tanto contenido estatico
    como dinamico
    −   Contenido estatico: HTML, XML
    −   Contenido dinamico: código de
        programación, y JavaBeans, custom tags


                                                 13
Código de ejemplo JSP
<html>
   Hello World!
 <br>
 <jsp:useBean id="clock"
              class=“calendar.JspCalendar” />
  Today is
 <ul>
 <li>Day of month: <%= clock.getDayOfMonth() %>
 <li>Year: <%= clock.getYear() %>
 </ul>
</html>




                                             14
JSP
       Servlets                        JSP

•
    Codigo HTML en          •
                                Código Java en HTML
    java                    •
                                Texto estructurado
•
    Cualquier forma de      •
                                Muy facil de construir
    Data                        la pagina web para el
•
    No es facil para el         autor
    autor construir una     •
                                El codigo es compilado
    pagina Web                  en un servlet




                                                    15
Beneficios JSP

    Contenido y logica para mostrar el contenido
    estan separados

    Simplifica el desarrollo con JSP, JavaBeans y
    custom tags

    Soporta la reutilizacion de software a traves
    de componentes

    Se recompila automaticamente cuando los
    cambios son hechos en el codigo JSP

    Facililidad de uso para el autor de paginas
    web

    Independiente de la plataforma
                                                    16
¿Cuando usar Servlet vs JSP?

    Extender la funcionalidad de un servidor
    Web para soportar un nuevo formato de
    archivo

    Generar objetos que no contienen HTML
    como son los graficos (pie charts)

    Evitar retornar HTML directamente
    desde tus servlets el mayor tiempo
    posible
                                           17
¿Debería yo usar Servlet or
JSP?

    En la practica, servlet y JSP son usados
    juntos
    −   via la arquitectura MVC (Model, View,
        Controller)
    −   Servlet maneja el Controller
    −   JSP maneja el View




                                                18
Modelo
Servlet Request &
    Response
                    19
Modelo Servlet Request y
Response
                                     Servlet Container
                                                Request




     Browser
               HTTP       Request
                                            Servlet
                          Response


                 Web                 Response
                 Server

                                                          20
¿Que es lo que hace el
Servlet?

    Recibe request del cliente(mayormente en la
    forma de HTTP request)

    Extrae cierta informacion del request

    Genera contenido o procesa logica de
    negocio (accesando a base de datos,
    invocando EJBs, etc)

    Crea y envía response al cliente (mayormente
    en la forma de HTTP) o hace forward del
    request a otro servlet o pagina JSP

                                                   21
Requests y Responses

    ¿Que es un request?
    −   Informacion que es envia del cliente al servidor
          
            Quien hizo el request
          
            Que data es enviada
          
            Que HTTP Headers son enviados

    ¿Que es un response?
    −   Informacion enviada al cliente desde el server
          
            Text(html, plain) o data binaria(image)
          
            HTTP headers, cookies, etc
                                                         22
HTTP

    HTTP request contiene
    − header
    − Un metodo
         
             Get: Data de entrada que es pasada como parte de un
             URL
         
             Post: Data de entrada es pasada dentro del mensaje
             body
         
             Put
         
             Header
    −   Información del request
                                                             23
HTTP GET y POST

    Son los request del cliente más comunes
    −   HTTP GET & HTTP POST

    GET requests:
    −   La informacion ingresada por el usuario es añadida a el
        URL en un query string
    −   Puede enviar solo una cantidad de data (limitado)
         
             .../servlet/ViewCourse?FirstName=Jose&LastName=Diaz

    POST requests:
    −   La informacion es enviada como data(no añadido a un
        URL)
    −   Puede enviar cualquier cantidad de informacion    24
Primer Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

Public class HelloServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
               HttpServletResponse response)
         throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<title>First Servlet</title>");
    out.println("<big>Hello Code Camp!</big>");
  }
}

                                               25
Interfaces y Classes
     de Servlet

                   26
Servlet Interfaces & Classes
                         Servlet



                    GenericServlet              HttpSession



                        HttpServlet


   ServletRequest                  ServletResponse



   HttpServletRequest              HttpServletResponse

                                                          27
Ciclo de vida
del Servlet

                28
Ciclo de vida del Servlet
                      Is Servlet Loaded?


           Http
         request
                                           Load          Invoke
                             No



            Http
         response            Yes
                                                          Run
                                                         Servlet
                                     Servlet Container

Client              Server

                                                                   29
Ciclo de vida desde la perspectiva
de métodos
                            service( )




         init( )                                 destroy( )
                             Ready
     Init parameters




                 doGet( )            doPost( )
                       Request parameters                     30
Métodos del Servlet

    Invocado por el contenedor
     − El contenedor controla el ciclo de vida del servlet

    Definido en
     − javax.servlet.GenericServlet class o
         
           init()
         
           destroy()
         
           service() – este es un metodo abstract
     − javax.servlet.http.HttpServlet class
         
           doGet(), doPost(), doXxx()
         
           service() - implementación
                                                             31
Métodos del Servlet

    init()
     −   Invocado una vez cuando el servlet es
         instanciado por primera vez
     −   Es idea para configurar algo en este metodo
          
              Configurando a una conección a base de datos

    destroy()
     −   Invocado antes que la instancia servlets sea
         removida
     −   Ideal para liberar recursos
          
              Cerrar una conección a base de datos
                                                             32
Ejemplo: init() de
CatalogServlet.java
public class CatalogServlet extends HttpServlet {
  private BookDB bookDB;

 // Perform any one-time operation for the servlet,
 // like getting database connection object.

  // Note: In this example, database connection object is assumed
  // to be created via other means (via life cycle event mechanism)
  // and saved in ServletContext object. This is to share a same
  // database connection object among multiple servlets.
  public void init() throws ServletException {
    bookDB = (BookDB)getServletContext().
                     getAttribute("bookDB");
    if (bookDB == null) throw new
      UnavailableException("Couldn't get database.");
  }
  ...
}                                                               33
Ejemplo: init() obteniendo
parametros de configuración
public void init(ServletConfig config) throws
  ServletException {
       super.init(config);
       String driver = getInitParameter("driver");
     String fURL = getInitParameter("url");
     try {
        openDBConnection(driver, fURL);
     } catch (SQLException e) {
         e.printStackTrace();
     } catch (ClassNotFoundException e){
         e.printStackTrace();
     }
}

                                                     34
Configurando parámetros de
inicialización en web.xml
<web-app>
    <servlet>
        <servlet-name>chart</servlet-name>
        <servlet-class>ChartServlet</servlet-class>
        <init-param>
            <param-name>driver</param-name>
            <param-value>
              COM.cloudscape.core.RmiJdbcDriver
            </param-value>
        </init-param>

        <init-param>
            <param-name>url</param-name>
            <param-value>
               jdbc:cloudscape:rmi:CloudscapeDB
            </param-value>
        </init-param>
    </servlet>
</web-app>

                                                      35
Ejemplo: destroy()
public class CatalogServlet extends HttpServlet {
  private BookDB bookDB;

    public void init() throws ServletException {
      bookDB = (BookDB)getServletContext().
                       getAttribute("bookDB");
      if (bookDB == null) throw new
        UnavailableException("Couldn't get database.");
    }
    public void destroy() {
           bookDB = null;
    }
    ...
}
                                                     36
Métodos del Servlet

    service() javax.servlet.GenericServlet class
    −   Método abstracto

    service() in javax.servlet.http.HttpServlet class
    −   Metodo concreto(implementación)
    −   Delega a doGet(), doPost(), etc
    −   No sobreescribir este metodo

    doGet(), doPost(), doXxx() en
    javax.servlet.http.HttpServlet
    −   Maneja HTTP GET, POST, etc. requests
    −   Sobreescribe estos metodos en tu servlet para darle
        un comportamiento particular
                                                          37
service() &
doGet()/doPost()

    El método service() toma requests y
    responses genericos:
    −   service(ServletRequest request,
               ServletResponse response)

    doGet() o doPost() toman HTTP
    requests y responses:
    −   doGet(HttpServletRequest request,
             HttpServletResponse response)
    −   doPost(HttpServletRequest request,
             HttpServletResponse response)
                                             38
Service() Method
                                 GenericServlet
               Server              subclass
                                     Subclass of
 Request                          GenericServlet class



                                      Service( )



 Response




        Key:            Implemented by subclass          39
Métodos doGet() y doPost()
                Server           HttpServlet subclass


                                                   doGet( )
   Request



                                Service( )



   Response                                         doPost( )



              Key:       Implemented by subclass
                                                              40
Tareas que tu haces en
doGet() & doPost()

    Extraes informacion enviada del cliente(parametro
    HTTP) desde el HTTP request

    Set (Save) y get (read) atributos en/desde objetos
    segun el scope (request, session)

    Ejecutar logica de negocios o acceso a base de datos

    Opcionalmente hacer forward del request a otro recurso
    Web u otros componentes Web (Servlet o JSP)

    Completar mensajes HTTP response y enviar este a el
    cliente


                                                         41
Ejemplo: Simple doGet()
 import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

Public class HelloServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
                       HttpServletResponse response)
                 throws ServletException, IOException {

        // Just send back a simple HTTP response
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<title>First Servlet</title>");
        out.println("<big>Hello J2EE Programmers! </big>");
    }
}

                                                         42
Ejemplo: doGet() Sofisticado
public void doGet (HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException {

        // Read session-scope attribute “message”
        HttpSession session = request.getSession(true);
      ResourceBundle messages = (ResourceBundle)session.getAttribute("messages");

       // Set headers and buffer size before accessing the Writer
       response.setContentType("text/html");
       response.setBufferSize(8192);
       PrintWriter out = response.getWriter();

       // Then write the response (Populate the header part of the response)
       out.println("<html>" +
                   "<head><title>" + messages.getString("TitleBookDescription") +
                   "</title></head>");

       // Get the dispatcher; it gets the banner to the user
       RequestDispatcher dispatcher =
              getServletContext().getRequestDispatcher("/banner");

       if (dispatcher != null)
              dispatcher.include(request, response);


                                                                                    43
Ejemplo: doGet() Sofisticado
     // Get the identifier of the book to display (Get HTTP parameter)
     String bookId = request.getParameter("bookId");
     if (bookId != null) {

        // and the information about the book (Perform business logic)
        try {
           BookDetails bd = bookDB.getBookDetails(bookId);
           Currency c = (Currency)session.getAttribute("currency");
           if (c == null) {
              c = new Currency();
              c.setLocale(request.getLocale());
              session.setAttribute("currency", c);
           }
           c.setAmount(bd.getPrice());

           // Print out the information obtained
           out.println("...");
        } catch (BookNotFoundException ex) {
                 response.resetBuffer();
                 throw new ServletException(ex);
        }

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

                                                                         44
Pasos para completar HTTP
Response

    Llenar Response headers

    Establecer algunas propiedades del
    response
    −   Buffer size

    Obtener un objeto output stream desde el
    response

    Escribir el contenido a dicho output
    stream
                                           45
Ejemplo: Simple Response
Public class HelloServlet extends HttpServlet {
 public void doGet(HttpServletRequest request,
                       HttpServletResponse response)
                throws ServletException, IOException {

        // Fill response headers
        response.setContentType("text/html");
        // Set buffer size
        response.setBufferSize(8192);
        // Get an output stream object from the response
        PrintWriter out = response.getWriter();
        // Write body content to output stream
        out.println("<title>First Servlet</title>");
        out.println("<big>Hello J2EE Programmers! </big>");
    }
}

                                                        46
Scope Objects


                47
Scope Objects

    Permite compartir información a traves de
    componentes web via atributos mantenidos en estos
    Scope objects
     − Atributos son pares de la forma nombre/objeto

    Atributos mantenidos en estos Scope objets son
    accesado a traves de
     − getAttribute() & setAttribute()

    4 Scope objects son definidos
     − Contexto web, session, request, page




                                                        48
Cuatro Scope Objects:
Accesibilidad

    Contexto Web(ServletContext)
     − Accesible desde componentes Web que estan dentro de un
       contexto

    Session
     − Accesible desde componentes web que manejan un request
       que pertenece a la session

    Request
     − Accesible desde componentes web que manejan el request

    Page
     −   Accesible desde paginas JSP que han creado el objeto



                                                                49
Cuatro Scope Objects:
Class

    Web context
    −   javax.servlet.ServletContext

    Session
    −   javax.servlet.http.HttpSession

    Request
    −   Subtipo de javax.servlet.ServletRequest:
        javax.servlet.http.HttpServletRequest

    Page
    −   javax.servlet.jsp.PageContext
                                                   50
Web Context
(ServletContext)
                   51
¿Para que es un ServletContext ?

    Usado por servlets para
     −   Establecer (Set) y obtener (get) objetos de scope context (o
         application) y obtener el valor de sus atributos
     −   Obtener un request dispatcher
           
             Para hacer forward o incluir un componente web
     −   Accesar a parametros de inicializacion del contexto web
         establecidos en el web.xml
     −   Accesar a recursos Web asociados con el contexto Web
     −   Log
     −   Accesar a otra informacion miscelanea




                                                                        52
Scope de ServletContext

    El scope o alcance es
     −   Compartido por todos los servlets y paginas JSP dentro
         de una “aplicación web"
          
            Esto es el porque de ser llamado “scope application”
     −   Una “aplicación web" es una colección de servlets y
         contenido instalado bajo un subconjunto especifico de
         URL namespaces y posiblemente instalado via un *.war
          
            Todos los servlets en la aplicación web BookStore
            comparten el mismo objeto ServletContext
     −   Hay un objeto ServletContext por “aplicación web" y por
         Java virtual machine



                                                                   53
ServletContext:
      Web Application Scope

Client 1

                      ServletContext
             server



                        application
 Client 2




                                       54
¿Como accesar al objeto
ServletContext?

    Dentro de tu codigo usando
    getServletContext()

    Dentro del codigo de un filtro de servlet,
    llamando a, getServletContext()

    El ServletContext es contenido en el objeto
    ServletConfig, el cual es provisto por el web
    server a un servlet cuando este es
    inicializado
    −   init (ServletConfig servletConfig) en la interface
        Servlet                                              55
Ejemplo: Obteniendo Attribute
Value de ServletContext
public class CatalogServlet extends HttpServlet {
  private BookDB bookDB;
  public void init() throws ServletException {
    // Get context-wide attribute value from
    // ServletContext object
    bookDB = (BookDB)getServletContext().
                     getAttribute("bookDB");
    if (bookDB == null) throw new
      UnavailableException("Couldn't get database.");
  }
}

                                                  56
Ejemplo: Obteniendo y usando el
objeto RequestDispatcher
public void doGet (HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException {

       HttpSession session = request.getSession(true);
             ResourceBundle messages = (ResourceBundle)session.getAttribute("messages");

       // set headers and buffer size before accessing the Writer
       response.setContentType("text/html");
           response.setBufferSize(8192);
           PrintWriter out = response.getWriter();

       // then write the response
       out.println("<html>" +
                   "<head><title>" + messages.getString("TitleBookDescription") +
                   "</title></head>");

       // Get the dispatcher; it gets the banner to the user
       RequestDispatcher dispatcher =
              session.getServletContext().getRequestDispatcher("/banner");

       if (dispatcher != null)
              dispatcher.include(request, response);
       ...

                                                                                57
Ejemplo: Logging
public void doGet (HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException {

       ...
       getServletContext().log(“Life is good!”);
       ...
       getServletContext().log(“Life is bad!”, someException);




                                                                 58
Session
(HttpSession)
                59
¿Porqué HttpSession?

    Necesidad de un medio para mantener
    información del cliente a traves de una
    serie de request desde el mismo
    usuario (u originado desde el mismo
    browser) en un periodo de tiempo
    −   Ejemplo: Online shopping cart

    HttpSession mantiene el estado del
    cliente
    −   Usado por Servlets para establecer y obtener
        los valores de atributos del session scope
                                                       60
¿Como obtener HttpSession?

    via el metodo getSession() del objeto
    Request (HttpServletRequest)




                                            61
Ejemplo: HttpSession
public class CashierServlet extends HttpServlet {
  public void doGet (HttpServletRequest request,
                     HttpServletResponse response)
              throws ServletException, IOException {

    // Get the user's session and shopping cart
    HttpSession session = request.getSession();
    ShoppingCart cart =
      (ShoppingCart)session.getAttribute("cart");
    ...
    // Determine the total price of the user's books
    double total = cart.getTotal();




                                                  62
Servlet Request
(HttpServletRequest)

                       63
¿Qué es Servlet Request?

    Contiene información pasada del cliente a el servlet

    Todos los servlet requests implementan la interface ServletRequest el
    cual define metodos para accesar a
     −   Parametros enviados por el Cliente
     −   Atributos nombre/objeto
     −   Localidades
     −   Cliente y servidor
     −   Input stream
     −   Información del protocolo
     −   Content type
     −   Si el request ha sido hecho de una conexión segura (HTTPS)




                                                                      64
Requests
data,
client, server, header
servlet itself
       Request            Servlet 1



                          Servlet 2



      Response            Servlet 3


                         Web Server
                                      65
Obteniendo parametros
enviados por el cliente

    Un request puede venir con cualquier numero de
    parametros enviados por el cliente

    Los parametros son enviados de dos formas:
     − GET: como un query string, añadido a un URL
     − POST: como data POST codificada, no aparece en el
       URL

    getParameter("paraName")
     − Retorna el valor de paraName
     − Retorna null si el parametro no esta presente
     − Trabaja indenticamente para request GET y POST



                                                           66
Un ejemplo de Formulario
usando GET
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE>Collecting Three Parameters</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Please Enter Your Information</H1>

<FORM ACTION="/sample/servlet/ThreeParams">
  First Name: <INPUT TYPE="TEXT" NAME="param1"><BR>
  Last Name:   <INPUT TYPE="TEXT" NAME="param2"><BR>
  Class Name: <INPUT TYPE="TEXT" NAME="param3"><BR>
  <CENTER>
    <INPUT TYPE="SUBMIT">
  </CENTER>
</FORM>

</BODY>
</HTML>


                                                                 67
Un formulario usando GET




                           68
El servlet: Get
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet that reads three parameters from the html form */
public class ThreeParams extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
                    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Your Information";
    out.println("<HTML>" +
                "<BODY BGCOLOR="#FDF5E6">n" +
                "<H1 ALIGN=CENTER>" + title + "</H1>n" +
                "<UL>n" +
                " <LI><B>First Name in Response</B>: "
                + request.getParameter("param1") + "n" +
                " <LI><B>Last Name in Response</B>: "
                + request.getParameter("param2") + "n" +
                " <LI><B>NickName in Response</B>: "
                + request.getParameter("param3") + "n" +
                "</UL>n" +
                "</BODY></HTML>");
  }
}

                                                                       69
Un formulario usando POST
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE>A Sample FORM using POST</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">A Sample FORM using POST</H1>
<FORM ACTION="/sample/servlet/ShowParameters" METHOD="POST">
  Item Number: <INPUT TYPE="TEXT" NAME="itemNum"><BR>
  Quantity: <INPUT TYPE="TEXT" NAME="quantity"><BR>
  Price Each: <INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR>
  First Name: <INPUT TYPE="TEXT" NAME="firstName"><BR>
  <TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR>
  Credit Card Number:
  <INPUT TYPE="PASSWORD" NAME="cardNum"><BR>
  <CENTER>
    <INPUT TYPE="SUBMIT" VALUE="Submit Order">
  </CENTER>
</FORM>
</BODY>
</HTML>


                                                                 70
un formulario usando POST




                            71
Servlet: POST
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShowParameters extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
                    throws ServletException, IOException {
     ...
  }
  public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
                   throws ServletException, IOException {
        doGet(request, response);
    }
}




                                                             72
Quien establece atributos Object/
value

    Request attributes pueden ser establecidos en dos formas
     − El contenedor de servlets por si mismo establece atributos
       para hacer disponible esta información acerca de un
       request
         
           Ejemplo: atributo javax.servlet.request.X509Certificate
           para HTTPS
     − Establecido por codigo asi
         
           void setAttribute(java.lang.String name,
           java.lang.Object o)
         
           Embebido en un request antes de ser llamado un
           RequestDispatcher

                                                                73
Obteniendo información Local
public void doGet (HttpServletRequest request,
                   HttpServletResponse response)
        throws ServletException, IOException {

      HttpSession session = request.getSession();
      ResourceBundle messages =

  (ResourceBundle)session.getAttribute("messages");

      if (messages == null) {
         Locale locale=request.getLocale();
         messages = ResourceBundle.getBundle(
                "messages.BookstoreMessages", locale);
         session.setAttribute("messages", messages);
      }




                                                         74
Obteniendo información del
Cliente

    El Servlet puede obtener información
    del cliente
    −   String request.getRemoteAddr()
         
             Obtiene IP Address
    −   String request.getRemoteHost()
         
             Obtiene nombre del cliente




                                           75
Obteniendo información del
server

    El Servlet puede obtener información
    del servidor:
    −   String request.getServerName()
         
             e.g. "www.sun.com"
    −   int request.getServerPort()
         
             e.g. Port number "8080"




                                           76
Obteniendo información Misc.

    Input stream
    −   ServletInputStream getInputStream()
    −   java.io.BufferedReader getReader()

    Protocol
    −   java.lang.String getProtocol()

    Content type
    −   java.lang.String getContentType()

    Es seguro o no(if it is HTTPS or not)
    −   boolean isSecure()
                                              77
HTTPServletRequest
                     78
¿Qué es HTTP Servlet Request?

    Contiene data pasada del cliente HTTP a el servlet HTTP

    Creado por contenedor de servlets y pasado al servlet como
    parametros de los metodos doGet() o doPost()

    HttpServletRequest es una extension de ServletRequest y
    provee metodos adicionales para accesar a
     −   HTTP request URL
          
            Context, servlet, path, query information
     −   Misc. HTTP Request header information
     −   Authentication type & User security information
     −   Cookies
     −   Session


                                                              79
HTTP Request URL

    Contiene las siguientes partes
    −   http://[host]:[port]/[request path]?[query string]




                                                             80
HTTP Request URL: [request path]

    http://[host]:[port]/[request path]?[query string]

    [request path] es hecho de
    −   Context: /<contexto de la aplicación web>
    −   Servlet name: /<component alias>
    −   Path information: el resto

    Ejemplos
    −   http://localhost:8080/hello1/greeting
    −   http://localhost:8080/hello1/greeting.jsp
    −   http://daydreamer/catalog/lawn/index.html


                                                    81
HTTP Request URL: [query string]

    http://[host]:[port]/[request path]?[query string]

    [query string] son compuestos por un conjunto de parametros y valores
    que el usuario ingreso

    Dos maneras de crear query strings
     −   Un query string pued aparecer explicitamente en una pagina web
          
            <a href="/bookstore1/catalog?Add=101">Add To Cart</a>
          
              String bookId = request.getParameter("Add");
     −   Un query string es añadido a un URL cuando un formulario es
         submiteado usando el metodo GET HTTP
           
             http://localhost/hello1/greeting?username=Monica+Clinton
          
              String userName=request.getParameter(“username”)



                                                                        82
Context, Path, Query, Parameter
Methods

    String getContextPath()

    String getQueryString()

    String getPathInfo()

    String getPathTranslated()




                                 83
HTTP Request Headers

    HTTP requests incluyen headers los
    cuales proveen información extra acerca
    del request

    Ejemplo de HTTP 1.1 Request:
    GET /search? keywords= servlets+ jsp HTTP/ 1.1
    Accept: image/ gif, image/ jpg, */*
    Accept-Encoding: gzip
    Connection: Keep- Alive
    Cookie: userID= id456578
    Host: www.sun.com
    Referer: http:/www.sun.com/codecamp.html
    User-Agent: Mozilla/ 4.7 [en] (Win98; U)
                                                     84
HTTP Request Headers

    Accept
     − Indica los tipos MIME que el browser puede
       manejar

    Accept-Encoding
     − Indica encoding(e. g., gzip or compress) que el
       browser puede manejar

    Authorization
     − Identificación del usuario para paginas protegidas
     − En lugar de HTTP authorization, usa HTML forms
       para enviar username/password y almacenar la
       informacion en un objeto session
                                                            85
HTTP Request Headers

    Connection
     − En HTTP 1.1, la conexión persistentes es por
       defecto
     − Servlets deben de configurar Content-Length con
       setContentLength (usar ByteArrayOutputStream
       para determinar longitud de salida) para soportar
       conexiones persistentes

    Cookie
     − Usar getCookies, no getHeader

    Host
     − Indica host dado en URL original.
     − Esto es requerido en HTTP 1.1.
                                                           86
HTTP Request Headers

    If-Modified-Since
      − Indica que cliente desea la pagina solo si esta ha
        sido modificada desde la ultima fecha especificada.
      − No manejar esta situacion directamente;
        implementar en su lugar getLastModified.

    Referer
      − URL de paginas web referidas.
      − Util para seguimiento de trafico

    User-Agent
      − String identifa el browser que esta haciendo el
        request.
      − Usar con extrema precaución!


                                                              87
HTTP Header Methods

    String getHeader(java.lang.String name)
     − Valor del request header como String

    java.util.Enumeration getHeaders(java.lang.String
    name)
     − Valores del request header especificado

    java.util.Enumeration getHeaderNames()
     − Nombres de los request headers

    int getIntHeader(java.lang.String name)
     − valor del request header especificado como int


                                                        88
Mostrando Request Headers
//Shows all the request headers sent on this particular request.
public class ShowRequestHeaders extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
                    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Servlet Example: Showing Request Headers";
    out.println("<HTML>" + ...
                "<B>Request Method: </B>" +
                request.getMethod() + "<BR>n" +
                "<B>Request URI: </B>" +
                request.getRequestURI() + "<BR>n" +
                "<B>Request Protocol: </B>" +
                request.getProtocol() + "<BR><BR>n" +
      ...
                "<TH>Header Name<TH>Header Value");
    Enumeration headerNames = request.getHeaderNames();
    while(headerNames.hasMoreElements()) {
      String headerName = (String)headerNames.nextElement();
      out.println("<TR><TD>" + headerName);
      out.println("    <TD>" + request.getHeader(headerName));
    }
    ...
  }
}


                                                                   89
Request Headers - Ejemplo




                            90
Authentication & User Security
Information

    String getRemoteUser()
     − Nombre del usuario si el servlet ha sido
        protegido por password, null en caso contrario

    String getAuthType()
     − Nombre del esquema de autenticación usado
        para proteger el servlet

    boolean isUserInRole(java.lang.String role)
     − ¿Esta el usuario incluido en role especificado?

    String getRemoteUser()
     − Login del usuario que esta haciendo el request,
        si el usuario ha sido autenticado, null en caso
        contrario.                                        91
Cookie Method (in
HTTPServletRequest)

    Cookie[] getCookies()
    −   Un array conteniendo todos los objetos Cookie
        que el ciente envia con el request




                                                        92
Servlet Response
(HttpServletResponse)

                        93
¿Qué es Servlet Response?

    Contiene data pasada del servlet a el cliente

    Todos los servlet responses implementan la
    interface ServletResponse
    −  Recupera un output stream
     − Indica content type
     − Indica el buffer output
     − Set información de localización

    HttpServletResponse extends ServletResponse
     − HTTP response status code
     − Cookies

                                                  94
Responses


        Request        Servlet 1



Response Structure:    Servlet 2
status code ,
headers and body.
       Response        Servlet 3


                      Web Server
                                   95
Response Structure

       Status Code

     Response Headers


      Response Body




                        96
Status Code in
Http Response
                 97
HTTP Response Status Codes

    ¿Porqué nosotros necesitamos HTTP
    response status code?
    −   Para hacer Forward a otra pagina
    −   Indicar si el recurso esta faltando
    −   Instruir al browser para usar copiado de
        informacion por cache




                                                   98
Metodos para establecer
HTTP Response Status Codes

    public void setStatus(int statusCode)
     −   Status codes son definidos en HttpServletResponse
     −   Status codes son numero organizados en cinco categorías
          
              100-199 Informational
          
              200-299 Successful
          
              300-399 Redirection
          
              400-499 Incomplete
          
              500-599 Server Error
     −   El codigo por defecto es 200 (OK)



                                                                   99
Ejemplo de HTTP Response
Status
HTTP/ 1.1 200 OK
Content-Type: text/ html
<! DOCTYPE ...>
<HTML
...
</ HTML>




                           100
Status Codes comunes

    200 (SC_OK)
     − Success
     − Default para servlets

    204 (SC_No_CONTENT)
     − Success pero sin body response
     − El Browser deberia mantener mostrando el
       contenido previo

    301 (SC_MOVED_PERMANENTLY)
     − El documento fue movido permanentemente
       (indicado en Location header)
    −   El browser ira a una nueva ubicacion
        automaticamente                           101
Status Codes Comunes

    302 (SC_MOVED_TEMPORARILY)
     − El mensaje es "Found"
     − El documento es movido temporalmente o caso
       contrario (indicado en Location header)
     − Browsers van a una nueva ubicacion
       automaticamente
     − Servlets deberian usar sendRedirect, no
       setStatus, cuando establecen este header

    401 (SC_UNAUTHORIZED)
     − El browser trato de acceder a una pagina
       protegida sin la autorizacion correspondiente

    404 (SC_NOT_FOUND)
     − Pagina no encontrada                            102
Metodos para enviar Error

    Error status codes (400-599) pueden
    ser usados en los metodos sendError

    public void sendError(int sc)
    −   El servidor puede dar el especial
        tratamiento del error

    public void sendError(int code, String
    message)
    −   Wrapea el mensaje dentro de un pequeño
        documento HTML
                                                 103
setStatus() & sendError()
try {
   returnAFile(fileName, out)
}
catch (FileNotFoundException e)
  { response.setStatus(response.SC_NOT_FOUND);
  out.println("Response body");
}

  has same effect as

try {
   returnAFile(fileName, out)
}
catch (FileNotFoundException e)
  {   response.sendError(response.SC_NOT_FOUND);
}

                                                   104
Header in
Http Response
                105
¿Porqué HTTP Response
Headers?

    Dar forwarding location

    Especificar cookies

    Proveer la fecha de modificacion de la pagina

    Instruir al browser para recargar la pagina
    despues de un periodo de tiempo

    Dar el tamaño del archivo de manera que la
    conexión persistente HTTP pueda ser usada

    Diseñar el tipo de documento que esta siendo
    generado

    Etc.
                                                    106
Metodos para establecer
Arbitrariamente Response
Headers

    public void setHeader( String headerName, String
    headerValue)
     − Establece un header.

    public void setDateHeader( String name, long millisecs)
     − Convierte milisegundos desde 1970 a un date string
       enformato GMT

    public void setIntHeader( String name, int headerValue)
     − Prevee la necesidad de convertir int a String antes de
       llamar a setHeader

    addHeader, addDateHeader, addIntHeader
     − Añade nuevas ocurrencias de header en lugar de
       reemplazarlos                                        107
Metodos para establecer
Response Headers comunes

    setContentType
     − Establece el contenido- tipo de header. Servlets
       casi siempre usan este.

    setContentLength
     − Establece la longitud del content header. Usado
       para conexiones persistentes HTTP.

    addCookie
     − Añade un valor a el Set- Cookie header.

    sendRedirect
     − Estable el Location header y cambia status
       code                                           108
HTTP 1.1 Response
Headers comunes

    Location
     − Especifica una nueva location del documento
     − Usar sendRedirect en lugar de establecer este
       directamente

     Refresh
     − Especifica un delay antes de que el browser
       automaticamente recargue la pagina

    Set-Cookie
     − Los cookies que el browser debe recordar. No
       establecer este header automaticamente.
     − Usar addCookie en su lugar.


                                                       109
continua

    Cache-Control (1.1) y Pragma (1.0)
    −   Un no-cache valor previene al browser de poner
        la pagina en cache. Envia ambos headers o
        chequea la version de HTTP.

    Content- Encoding
    −   La manera en que el documento es codificado.
        El Browser revierte esta codificacion antes de
        manejar el documento

    Content- Length
    −   El numero de bytes en el response. Usado para
        conexiones persistentes HTTP
                                                         110
Continua

    Content- Type
    −   El MIME type del documento que esta siendo
        retornado.
    −   Usa setContentType para establecer este
        header.

    Ultima modificación
    −   La ultima vez que el documento fue cambiado
    −   No establecer este header explicitamente.
    −   Proveer un metodo getLastModified en su lugar.
                                                     111
Ejemplo de codigo - Refresh

public class DateRefresh extends HttpServlet {
  public void doGet(HttpServletRequest req,
                    HttpServletResponse res)
       throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    res.setHeader("Refresh", "5");
    out.println(new Date().toString());
  }
}




                                             112
Body in
Http Response
                113
Escribiendo un Response
Body

    Un servlet casi siempre retorna un
    response body

    Response body puede ser un PrintWriter
    o un ServletOutputStream

    PrintWriter
    −   Usando response.getWriter()
    −   Para salida basada en caracteres

    ServletOutputStream
    −   Usando response.getOutputStream()
    −   Para data binaria (imagenes)         114
Manejando Errores


                    115
Manejando Errores

    El contenedor web genera una pagina de
    error por defecto

    Tu puedes proporcionar tu propia pagina
    de error

    Pasos para manejar errores
    −   Crea paginas de error html apropiados para
        condiciones de error
    −   Modificar el web.xml


                                                     116
Ejemplo: Establecer paginas
de error en web.xml
<error-page>
 <exception-type>
  exception.BookNotFoundException
 </exception-type>
 <location>/errorpage1.html</location>
</error-page>
<error-page>
 <exception-type>
  exception.BooksNotFoundException
 </exception-type>
 <location>/errorpage2.html</location>
</error-page>
<error-page>
 <exception-type>exception.OrderException</exception-type>
 <location>/errorpage3.html</location>
</error-page>                                              117
¡Gracias!


            118

More Related Content

What's hot

Design Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codeDesign Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codePaulo Gandra de Sousa
 
Cualidades y elementos de un buen patron de diseño
Cualidades y elementos de un buen patron de diseñoCualidades y elementos de un buen patron de diseño
Cualidades y elementos de un buen patron de diseñoAtahualpa Acosta
 
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator PatternDesign Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator Patterneprafulla
 
Advanced mechanisms for dynamic content delivery
Advanced mechanisms for dynamic content deliveryAdvanced mechanisms for dynamic content delivery
Advanced mechanisms for dynamic content deliveryAakash587
 
Curso Uml 2.1 Diagramas De Cu Y Clases
Curso Uml   2.1 Diagramas De Cu Y ClasesCurso Uml   2.1 Diagramas De Cu Y Clases
Curso Uml 2.1 Diagramas De Cu Y ClasesEmilio Aviles Avila
 
32- Android, Desarrollo de Aplicaciones Moviles, Importancia del Mockup
32- Android, Desarrollo de Aplicaciones Moviles, Importancia del Mockup32- Android, Desarrollo de Aplicaciones Moviles, Importancia del Mockup
32- Android, Desarrollo de Aplicaciones Moviles, Importancia del MockupPedro Antonio Villalta (Pavillalta)
 
Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalizationsusant sahu
 
Hibernate start (하이버네이트 시작하기)
Hibernate start (하이버네이트 시작하기)Hibernate start (하이버네이트 시작하기)
Hibernate start (하이버네이트 시작하기)visual khh
 
Sesion 2 1 modelo del negocio
Sesion 2 1 modelo del negocioSesion 2 1 modelo del negocio
Sesion 2 1 modelo del negocioJulio Pari
 
Ingeniería derequerimientos
Ingeniería derequerimientosIngeniería derequerimientos
Ingeniería derequerimientosKaddy Hernandez
 
Colecciones en Java
Colecciones en JavaColecciones en Java
Colecciones en JavaRonny Parra
 

What's hot (20)

Design Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codeDesign Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID code
 
Cualidades y elementos de un buen patron de diseño
Cualidades y elementos de un buen patron de diseñoCualidades y elementos de un buen patron de diseño
Cualidades y elementos de un buen patron de diseño
 
Design Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator PatternDesign Patterns - 01 Introduction and Decorator Pattern
Design Patterns - 01 Introduction and Decorator Pattern
 
Patron de diseño composite
Patron de diseño compositePatron de diseño composite
Patron de diseño composite
 
Advanced mechanisms for dynamic content delivery
Advanced mechanisms for dynamic content deliveryAdvanced mechanisms for dynamic content delivery
Advanced mechanisms for dynamic content delivery
 
Diagrama de clases y objetos
Diagrama de clases y objetosDiagrama de clases y objetos
Diagrama de clases y objetos
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 
Diagrama de dominio armando
Diagrama de dominio armandoDiagrama de dominio armando
Diagrama de dominio armando
 
Curso Uml 2.1 Diagramas De Cu Y Clases
Curso Uml   2.1 Diagramas De Cu Y ClasesCurso Uml   2.1 Diagramas De Cu Y Clases
Curso Uml 2.1 Diagramas De Cu Y Clases
 
Trabajo de sistemas expertos
Trabajo de sistemas expertosTrabajo de sistemas expertos
Trabajo de sistemas expertos
 
32- Android, Desarrollo de Aplicaciones Moviles, Importancia del Mockup
32- Android, Desarrollo de Aplicaciones Moviles, Importancia del Mockup32- Android, Desarrollo de Aplicaciones Moviles, Importancia del Mockup
32- Android, Desarrollo de Aplicaciones Moviles, Importancia del Mockup
 
Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalization
 
Hibernate start (하이버네이트 시작하기)
Hibernate start (하이버네이트 시작하기)Hibernate start (하이버네이트 시작하기)
Hibernate start (하이버네이트 시작하기)
 
Sesion 2 1 modelo del negocio
Sesion 2 1 modelo del negocioSesion 2 1 modelo del negocio
Sesion 2 1 modelo del negocio
 
Modelado del negocio
Modelado del negocioModelado del negocio
Modelado del negocio
 
02 modelo delnegocio
02 modelo delnegocio02 modelo delnegocio
02 modelo delnegocio
 
Casos de uso de negocios y sistemas
Casos de uso de negocios y sistemasCasos de uso de negocios y sistemas
Casos de uso de negocios y sistemas
 
Ingeniería derequerimientos
Ingeniería derequerimientosIngeniería derequerimientos
Ingeniería derequerimientos
 
Modelo rup
Modelo rupModelo rup
Modelo rup
 
Colecciones en Java
Colecciones en JavaColecciones en Java
Colecciones en Java
 

Viewers also liked

APLICACIONES EMPRESARIALES
APLICACIONES EMPRESARIALESAPLICACIONES EMPRESARIALES
APLICACIONES EMPRESARIALESDarwin Durand
 
Presentación Spring Boot en Autentia
Presentación Spring Boot en AutentiaPresentación Spring Boot en Autentia
Presentación Spring Boot en AutentiaJorge Pacheco Mengual
 
Java - Sintaxis Básica 2015
Java - Sintaxis Básica 2015Java - Sintaxis Básica 2015
Java - Sintaxis Básica 2015Renny Batista
 
PERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOSPERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOSDarwin Durand
 
Ejemplos Borland C++ Builder
Ejemplos Borland C++ BuilderEjemplos Borland C++ Builder
Ejemplos Borland C++ BuilderDarwin Durand
 
Programación Orientada a Objetos en Java - Parte I 2015
Programación Orientada a Objetos en Java - Parte I 2015Programación Orientada a Objetos en Java - Parte I 2015
Programación Orientada a Objetos en Java - Parte I 2015Renny Batista
 
Fundamentos de Sistema- >Tema II
Fundamentos de Sistema- >Tema IIFundamentos de Sistema- >Tema II
Fundamentos de Sistema- >Tema IIRenny Batista
 
Html - Tema 2: Enlaces, Imágenes y Listas
Html - Tema 2: Enlaces, Imágenes y ListasHtml - Tema 2: Enlaces, Imágenes y Listas
Html - Tema 2: Enlaces, Imágenes y ListasRenny Batista
 
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERINSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERDarwin Durand
 
Arquitectura y diseño de aplicaciones Java EE
Arquitectura y diseño de aplicaciones Java EEArquitectura y diseño de aplicaciones Java EE
Arquitectura y diseño de aplicaciones Java EECarlos Gavidia-Calderon
 
Diseño adaptativo y responsive
Diseño adaptativo y responsiveDiseño adaptativo y responsive
Diseño adaptativo y responsiveRenny Batista
 
Elemento tipicos de las interfaces graficas de usuario
Elemento tipicos de las interfaces graficas de usuario Elemento tipicos de las interfaces graficas de usuario
Elemento tipicos de las interfaces graficas de usuario ivancmontero
 
Diagramas de Flujos de Datos
Diagramas de Flujos de DatosDiagramas de Flujos de Datos
Diagramas de Flujos de DatosRenny Batista
 

Viewers also liked (20)

APLICACIONES EMPRESARIALES
APLICACIONES EMPRESARIALESAPLICACIONES EMPRESARIALES
APLICACIONES EMPRESARIALES
 
Taller MVC
Taller MVCTaller MVC
Taller MVC
 
Presentación Spring Boot en Autentia
Presentación Spring Boot en AutentiaPresentación Spring Boot en Autentia
Presentación Spring Boot en Autentia
 
Java - Sintaxis Básica 2015
Java - Sintaxis Básica 2015Java - Sintaxis Básica 2015
Java - Sintaxis Básica 2015
 
03 java poo_parte_2
03 java poo_parte_203 java poo_parte_2
03 java poo_parte_2
 
Java colecciones
Java coleccionesJava colecciones
Java colecciones
 
Sistemas Operativos
Sistemas OperativosSistemas Operativos
Sistemas Operativos
 
PERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOSPERSISTENCIA BASADA EN ARCHIVOS
PERSISTENCIA BASADA EN ARCHIVOS
 
Ejemplos Borland C++ Builder
Ejemplos Borland C++ BuilderEjemplos Borland C++ Builder
Ejemplos Borland C++ Builder
 
Servlet
ServletServlet
Servlet
 
CREACION DE TABLAS
CREACION DE TABLASCREACION DE TABLAS
CREACION DE TABLAS
 
Programación Orientada a Objetos en Java - Parte I 2015
Programación Orientada a Objetos en Java - Parte I 2015Programación Orientada a Objetos en Java - Parte I 2015
Programación Orientada a Objetos en Java - Parte I 2015
 
Fundamentos de Sistema- >Tema II
Fundamentos de Sistema- >Tema IIFundamentos de Sistema- >Tema II
Fundamentos de Sistema- >Tema II
 
05 java excepciones
05 java excepciones05 java excepciones
05 java excepciones
 
Html - Tema 2: Enlaces, Imágenes y Listas
Html - Tema 2: Enlaces, Imágenes y ListasHtml - Tema 2: Enlaces, Imágenes y Listas
Html - Tema 2: Enlaces, Imágenes y Listas
 
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERINSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
 
Arquitectura y diseño de aplicaciones Java EE
Arquitectura y diseño de aplicaciones Java EEArquitectura y diseño de aplicaciones Java EE
Arquitectura y diseño de aplicaciones Java EE
 
Diseño adaptativo y responsive
Diseño adaptativo y responsiveDiseño adaptativo y responsive
Diseño adaptativo y responsive
 
Elemento tipicos de las interfaces graficas de usuario
Elemento tipicos de las interfaces graficas de usuario Elemento tipicos de las interfaces graficas de usuario
Elemento tipicos de las interfaces graficas de usuario
 
Diagramas de Flujos de Datos
Diagramas de Flujos de DatosDiagramas de Flujos de Datos
Diagramas de Flujos de Datos
 

Similar to SERVLET BASICS

Introducción al desarrollo de aplicaciones web en Java
Introducción al desarrollo de aplicaciones web en JavaIntroducción al desarrollo de aplicaciones web en Java
Introducción al desarrollo de aplicaciones web en JavaEudris Cabrera
 
[ES] Introdución al desarrollo de aplicaciones web en java
[ES] Introdución al desarrollo de aplicaciones  web en java[ES] Introdución al desarrollo de aplicaciones  web en java
[ES] Introdución al desarrollo de aplicaciones web en javaEudris Cabrera
 
[ES] Introducción a las Aplicaciones Web con Java
[ES] Introducción a las Aplicaciones Web con Java[ES] Introducción a las Aplicaciones Web con Java
[ES] Introducción a las Aplicaciones Web con JavaEudris Cabrera
 
5 c arquitecturas_aplicaciones_web
5 c arquitecturas_aplicaciones_web5 c arquitecturas_aplicaciones_web
5 c arquitecturas_aplicaciones_webJuy JLopez
 
Programación en Internet
Programación en InternetProgramación en Internet
Programación en InternetFernando Solis
 
Serlets y jsp prev
Serlets y jsp prevSerlets y jsp prev
Serlets y jsp prevjtk1
 
Serlets y jsp pre
Serlets y jsp preSerlets y jsp pre
Serlets y jsp prejtk1
 
Curso Java Avanzado 1 IntroduccióN Al Desarrollo Web
Curso Java Avanzado   1 IntroduccióN Al Desarrollo WebCurso Java Avanzado   1 IntroduccióN Al Desarrollo Web
Curso Java Avanzado 1 IntroduccióN Al Desarrollo WebEmilio Aviles Avila
 
Plataforma de programación Java
Plataforma de programación JavaPlataforma de programación Java
Plataforma de programación JavaAntonio Contreras
 
Curso: Programación Web con Tecnología Java
Curso:  	Programación Web con Tecnología JavaCurso:  	Programación Web con Tecnología Java
Curso: Programación Web con Tecnología Javaalvaro alcocer sotil
 
Manual 2014 i 04 lenguaje de programación ii (0870)
Manual 2014 i 04 lenguaje de programación ii (0870)Manual 2014 i 04 lenguaje de programación ii (0870)
Manual 2014 i 04 lenguaje de programación ii (0870)Robert Rayco Quiroz
 
[ES] Fundamentos de Java Enterprise Edition
[ES] Fundamentos de Java Enterprise Edition [ES] Fundamentos de Java Enterprise Edition
[ES] Fundamentos de Java Enterprise Edition Eudris Cabrera
 
Aplicaciones Web SPA con WebAPI y TypeScript
Aplicaciones Web SPA con WebAPI y TypeScriptAplicaciones Web SPA con WebAPI y TypeScript
Aplicaciones Web SPA con WebAPI y TypeScriptLuis Guerrero
 
1/9 Curso JEE5, Soa, Web Services, ESB y XML
1/9 Curso JEE5, Soa, Web Services, ESB y XML1/9 Curso JEE5, Soa, Web Services, ESB y XML
1/9 Curso JEE5, Soa, Web Services, ESB y XMLJuan Carlos Rubio Pineda
 
introduccion-a-las-aplicaciones-web-y-tecnologia-java.ppt
introduccion-a-las-aplicaciones-web-y-tecnologia-java.pptintroduccion-a-las-aplicaciones-web-y-tecnologia-java.ppt
introduccion-a-las-aplicaciones-web-y-tecnologia-java.pptBYRONMIGUELSUBUYUCPA
 

Similar to SERVLET BASICS (20)

Eclipse
EclipseEclipse
Eclipse
 
Introducción al desarrollo de aplicaciones web en Java
Introducción al desarrollo de aplicaciones web en JavaIntroducción al desarrollo de aplicaciones web en Java
Introducción al desarrollo de aplicaciones web en Java
 
[ES] Introdución al desarrollo de aplicaciones web en java
[ES] Introdución al desarrollo de aplicaciones  web en java[ES] Introdución al desarrollo de aplicaciones  web en java
[ES] Introdución al desarrollo de aplicaciones web en java
 
[ES] Introducción a las Aplicaciones Web con Java
[ES] Introducción a las Aplicaciones Web con Java[ES] Introducción a las Aplicaciones Web con Java
[ES] Introducción a las Aplicaciones Web con Java
 
Desarrollo web
Desarrollo webDesarrollo web
Desarrollo web
 
5 c arquitecturas_aplicaciones_web
5 c arquitecturas_aplicaciones_web5 c arquitecturas_aplicaciones_web
5 c arquitecturas_aplicaciones_web
 
Charla
CharlaCharla
Charla
 
Programación en Internet
Programación en InternetProgramación en Internet
Programación en Internet
 
Serlets y jsp prev
Serlets y jsp prevSerlets y jsp prev
Serlets y jsp prev
 
Serlets y jsp pre
Serlets y jsp preSerlets y jsp pre
Serlets y jsp pre
 
Java Web - Servlet
Java Web - ServletJava Web - Servlet
Java Web - Servlet
 
Curso Java Avanzado 1 IntroduccióN Al Desarrollo Web
Curso Java Avanzado   1 IntroduccióN Al Desarrollo WebCurso Java Avanzado   1 IntroduccióN Al Desarrollo Web
Curso Java Avanzado 1 IntroduccióN Al Desarrollo Web
 
Plataforma de programación Java
Plataforma de programación JavaPlataforma de programación Java
Plataforma de programación Java
 
Curso: Programación Web con Tecnología Java
Curso:  	Programación Web con Tecnología JavaCurso:  	Programación Web con Tecnología Java
Curso: Programación Web con Tecnología Java
 
Manual 2014 i 04 lenguaje de programación ii (0870)
Manual 2014 i 04 lenguaje de programación ii (0870)Manual 2014 i 04 lenguaje de programación ii (0870)
Manual 2014 i 04 lenguaje de programación ii (0870)
 
[ES] Fundamentos de Java Enterprise Edition
[ES] Fundamentos de Java Enterprise Edition [ES] Fundamentos de Java Enterprise Edition
[ES] Fundamentos de Java Enterprise Edition
 
Aplicaciones Web SPA con WebAPI y TypeScript
Aplicaciones Web SPA con WebAPI y TypeScriptAplicaciones Web SPA con WebAPI y TypeScript
Aplicaciones Web SPA con WebAPI y TypeScript
 
1/9 Curso JEE5, Soa, Web Services, ESB y XML
1/9 Curso JEE5, Soa, Web Services, ESB y XML1/9 Curso JEE5, Soa, Web Services, ESB y XML
1/9 Curso JEE5, Soa, Web Services, ESB y XML
 
introduccion-a-las-aplicaciones-web-y-tecnologia-java.ppt
introduccion-a-las-aplicaciones-web-y-tecnologia-java.pptintroduccion-a-las-aplicaciones-web-y-tecnologia-java.ppt
introduccion-a-las-aplicaciones-web-y-tecnologia-java.ppt
 
Comenzando con GWT
Comenzando con GWTComenzando con GWT
Comenzando con GWT
 

More from Darwin Durand

Visual Studio.Net - Sql Server
Visual Studio.Net - Sql ServerVisual Studio.Net - Sql Server
Visual Studio.Net - Sql ServerDarwin Durand
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
EJEMPLOS DESARROLLADOS
EJEMPLOS DESARROLLADOSEJEMPLOS DESARROLLADOS
EJEMPLOS DESARROLLADOSDarwin Durand
 
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)Darwin Durand
 
CONEXION VISUAL STUDIO.NET - SQL SERVER
CONEXION VISUAL STUDIO.NET - SQL SERVERCONEXION VISUAL STUDIO.NET - SQL SERVER
CONEXION VISUAL STUDIO.NET - SQL SERVERDarwin Durand
 
CREACION DE DLL Y USO (Ejemplo desarrollado)
CREACION DE DLL Y USO (Ejemplo desarrollado)CREACION DE DLL Y USO (Ejemplo desarrollado)
CREACION DE DLL Y USO (Ejemplo desarrollado)Darwin Durand
 
SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)Darwin Durand
 
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOLCURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOLDarwin Durand
 
INDICES EN SQL SERVER
INDICES EN SQL SERVERINDICES EN SQL SERVER
INDICES EN SQL SERVERDarwin Durand
 
CREACION Y MANEJO DE LA BASE DE DATOS
CREACION Y MANEJO DE LA BASE DE DATOSCREACION Y MANEJO DE LA BASE DE DATOS
CREACION Y MANEJO DE LA BASE DE DATOSDarwin Durand
 

More from Darwin Durand (11)

Visual Studio.Net - Sql Server
Visual Studio.Net - Sql ServerVisual Studio.Net - Sql Server
Visual Studio.Net - Sql Server
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
EJEMPLOS DESARROLLADOS
EJEMPLOS DESARROLLADOSEJEMPLOS DESARROLLADOS
EJEMPLOS DESARROLLADOS
 
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
PROYECTO PRUEBA DE CONEXIONES (Mantenimiento)
 
CONEXION VISUAL STUDIO.NET - SQL SERVER
CONEXION VISUAL STUDIO.NET - SQL SERVERCONEXION VISUAL STUDIO.NET - SQL SERVER
CONEXION VISUAL STUDIO.NET - SQL SERVER
 
CREACION DE DLL Y USO (Ejemplo desarrollado)
CREACION DE DLL Y USO (Ejemplo desarrollado)CREACION DE DLL Y USO (Ejemplo desarrollado)
CREACION DE DLL Y USO (Ejemplo desarrollado)
 
SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)
 
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOLCURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
CURSO DE PROGRAMACION AVANZADA EN JAVA EN ESPAÑOL
 
INDICES EN SQL SERVER
INDICES EN SQL SERVERINDICES EN SQL SERVER
INDICES EN SQL SERVER
 
INTEGRIDAD DE DATOS
INTEGRIDAD DE DATOSINTEGRIDAD DE DATOS
INTEGRIDAD DE DATOS
 
CREACION Y MANEJO DE LA BASE DE DATOS
CREACION Y MANEJO DE LA BASE DE DATOSCREACION Y MANEJO DE LA BASE DE DATOS
CREACION Y MANEJO DE LA BASE DE DATOS
 

Recently uploaded

🦄💫4° SEM32 WORD PLANEACIÓN PROYECTOS DARUKEL 23-24.docx
🦄💫4° SEM32 WORD PLANEACIÓN PROYECTOS DARUKEL 23-24.docx🦄💫4° SEM32 WORD PLANEACIÓN PROYECTOS DARUKEL 23-24.docx
🦄💫4° SEM32 WORD PLANEACIÓN PROYECTOS DARUKEL 23-24.docxEliaHernndez7
 
6.-Como-Atraer-El-Amor-01-Lain-Garcia-Calvo.pdf
6.-Como-Atraer-El-Amor-01-Lain-Garcia-Calvo.pdf6.-Como-Atraer-El-Amor-01-Lain-Garcia-Calvo.pdf
6.-Como-Atraer-El-Amor-01-Lain-Garcia-Calvo.pdfMiNeyi1
 
SEXTO SEGUNDO PERIODO EMPRENDIMIENTO.pptx
SEXTO SEGUNDO PERIODO EMPRENDIMIENTO.pptxSEXTO SEGUNDO PERIODO EMPRENDIMIENTO.pptx
SEXTO SEGUNDO PERIODO EMPRENDIMIENTO.pptxYadi Campos
 
LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...
LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...
LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...JAVIER SOLIS NOYOLA
 
NUEVAS DIAPOSITIVAS POSGRADO Gestion Publica.pdf
NUEVAS DIAPOSITIVAS POSGRADO Gestion Publica.pdfNUEVAS DIAPOSITIVAS POSGRADO Gestion Publica.pdf
NUEVAS DIAPOSITIVAS POSGRADO Gestion Publica.pdfUPTAIDELTACHIRA
 
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICABIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICAÁngel Encinas
 
PINTURA DEL RENACIMIENTO EN ESPAÑA (SIGLO XVI).ppt
PINTURA DEL RENACIMIENTO EN ESPAÑA (SIGLO XVI).pptPINTURA DEL RENACIMIENTO EN ESPAÑA (SIGLO XVI).ppt
PINTURA DEL RENACIMIENTO EN ESPAÑA (SIGLO XVI).pptAlberto Rubio
 
ACTIVIDAD DIA DE LA MADRE FICHA DE TRABAJO
ACTIVIDAD DIA DE LA MADRE FICHA DE TRABAJOACTIVIDAD DIA DE LA MADRE FICHA DE TRABAJO
ACTIVIDAD DIA DE LA MADRE FICHA DE TRABAJOBRIGIDATELLOLEONARDO
 
PLAN DE REFUERZO ESCOLAR primaria (1).docx
PLAN DE REFUERZO ESCOLAR primaria (1).docxPLAN DE REFUERZO ESCOLAR primaria (1).docx
PLAN DE REFUERZO ESCOLAR primaria (1).docxlupitavic
 
proyecto de mayo inicial 5 añitos aprender es bueno para tu niño
proyecto de mayo inicial 5 añitos aprender es bueno para tu niñoproyecto de mayo inicial 5 añitos aprender es bueno para tu niño
proyecto de mayo inicial 5 añitos aprender es bueno para tu niñotapirjackluis
 
Lecciones 05 Esc. Sabática. Fe contra todo pronóstico.
Lecciones 05 Esc. Sabática. Fe contra todo pronóstico.Lecciones 05 Esc. Sabática. Fe contra todo pronóstico.
Lecciones 05 Esc. Sabática. Fe contra todo pronóstico.Alejandrino Halire Ccahuana
 
CALENDARIZACION DE MAYO / RESPONSABILIDAD
CALENDARIZACION DE MAYO / RESPONSABILIDADCALENDARIZACION DE MAYO / RESPONSABILIDAD
CALENDARIZACION DE MAYO / RESPONSABILIDADauxsoporte
 
Dinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes dDinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes dstEphaniiie
 
GUIA DE CIRCUNFERENCIA Y ELIPSE UNDÉCIMO 2024.pdf
GUIA DE CIRCUNFERENCIA Y ELIPSE UNDÉCIMO 2024.pdfGUIA DE CIRCUNFERENCIA Y ELIPSE UNDÉCIMO 2024.pdf
GUIA DE CIRCUNFERENCIA Y ELIPSE UNDÉCIMO 2024.pdfPaolaRopero2
 
Programacion Anual Matemática5 MPG 2024 Ccesa007.pdf
Programacion Anual Matemática5    MPG 2024  Ccesa007.pdfProgramacion Anual Matemática5    MPG 2024  Ccesa007.pdf
Programacion Anual Matemática5 MPG 2024 Ccesa007.pdfDemetrio Ccesa Rayme
 
2 REGLAMENTO RM 0912-2024 DE MODALIDADES DE GRADUACIÓN_.pptx
2 REGLAMENTO RM 0912-2024 DE MODALIDADES DE GRADUACIÓN_.pptx2 REGLAMENTO RM 0912-2024 DE MODALIDADES DE GRADUACIÓN_.pptx
2 REGLAMENTO RM 0912-2024 DE MODALIDADES DE GRADUACIÓN_.pptxRigoTito
 
2024 KIT DE HABILIDADES SOCIOEMOCIONALES.pdf
2024 KIT DE HABILIDADES SOCIOEMOCIONALES.pdf2024 KIT DE HABILIDADES SOCIOEMOCIONALES.pdf
2024 KIT DE HABILIDADES SOCIOEMOCIONALES.pdfMiguelHuaman31
 

Recently uploaded (20)

Supuestos_prácticos_funciones.docx
Supuestos_prácticos_funciones.docxSupuestos_prácticos_funciones.docx
Supuestos_prácticos_funciones.docx
 
🦄💫4° SEM32 WORD PLANEACIÓN PROYECTOS DARUKEL 23-24.docx
🦄💫4° SEM32 WORD PLANEACIÓN PROYECTOS DARUKEL 23-24.docx🦄💫4° SEM32 WORD PLANEACIÓN PROYECTOS DARUKEL 23-24.docx
🦄💫4° SEM32 WORD PLANEACIÓN PROYECTOS DARUKEL 23-24.docx
 
6.-Como-Atraer-El-Amor-01-Lain-Garcia-Calvo.pdf
6.-Como-Atraer-El-Amor-01-Lain-Garcia-Calvo.pdf6.-Como-Atraer-El-Amor-01-Lain-Garcia-Calvo.pdf
6.-Como-Atraer-El-Amor-01-Lain-Garcia-Calvo.pdf
 
SEXTO SEGUNDO PERIODO EMPRENDIMIENTO.pptx
SEXTO SEGUNDO PERIODO EMPRENDIMIENTO.pptxSEXTO SEGUNDO PERIODO EMPRENDIMIENTO.pptx
SEXTO SEGUNDO PERIODO EMPRENDIMIENTO.pptx
 
LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...
LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...
LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...
 
NUEVAS DIAPOSITIVAS POSGRADO Gestion Publica.pdf
NUEVAS DIAPOSITIVAS POSGRADO Gestion Publica.pdfNUEVAS DIAPOSITIVAS POSGRADO Gestion Publica.pdf
NUEVAS DIAPOSITIVAS POSGRADO Gestion Publica.pdf
 
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICABIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
 
PINTURA DEL RENACIMIENTO EN ESPAÑA (SIGLO XVI).ppt
PINTURA DEL RENACIMIENTO EN ESPAÑA (SIGLO XVI).pptPINTURA DEL RENACIMIENTO EN ESPAÑA (SIGLO XVI).ppt
PINTURA DEL RENACIMIENTO EN ESPAÑA (SIGLO XVI).ppt
 
ACTIVIDAD DIA DE LA MADRE FICHA DE TRABAJO
ACTIVIDAD DIA DE LA MADRE FICHA DE TRABAJOACTIVIDAD DIA DE LA MADRE FICHA DE TRABAJO
ACTIVIDAD DIA DE LA MADRE FICHA DE TRABAJO
 
PLAN DE REFUERZO ESCOLAR primaria (1).docx
PLAN DE REFUERZO ESCOLAR primaria (1).docxPLAN DE REFUERZO ESCOLAR primaria (1).docx
PLAN DE REFUERZO ESCOLAR primaria (1).docx
 
Presentacion Metodología de Enseñanza Multigrado
Presentacion Metodología de Enseñanza MultigradoPresentacion Metodología de Enseñanza Multigrado
Presentacion Metodología de Enseñanza Multigrado
 
proyecto de mayo inicial 5 añitos aprender es bueno para tu niño
proyecto de mayo inicial 5 añitos aprender es bueno para tu niñoproyecto de mayo inicial 5 añitos aprender es bueno para tu niño
proyecto de mayo inicial 5 añitos aprender es bueno para tu niño
 
Lecciones 05 Esc. Sabática. Fe contra todo pronóstico.
Lecciones 05 Esc. Sabática. Fe contra todo pronóstico.Lecciones 05 Esc. Sabática. Fe contra todo pronóstico.
Lecciones 05 Esc. Sabática. Fe contra todo pronóstico.
 
CALENDARIZACION DE MAYO / RESPONSABILIDAD
CALENDARIZACION DE MAYO / RESPONSABILIDADCALENDARIZACION DE MAYO / RESPONSABILIDAD
CALENDARIZACION DE MAYO / RESPONSABILIDAD
 
Dinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes dDinámica florecillas a María en el mes d
Dinámica florecillas a María en el mes d
 
Power Point: Fe contra todo pronóstico.pptx
Power Point: Fe contra todo pronóstico.pptxPower Point: Fe contra todo pronóstico.pptx
Power Point: Fe contra todo pronóstico.pptx
 
GUIA DE CIRCUNFERENCIA Y ELIPSE UNDÉCIMO 2024.pdf
GUIA DE CIRCUNFERENCIA Y ELIPSE UNDÉCIMO 2024.pdfGUIA DE CIRCUNFERENCIA Y ELIPSE UNDÉCIMO 2024.pdf
GUIA DE CIRCUNFERENCIA Y ELIPSE UNDÉCIMO 2024.pdf
 
Programacion Anual Matemática5 MPG 2024 Ccesa007.pdf
Programacion Anual Matemática5    MPG 2024  Ccesa007.pdfProgramacion Anual Matemática5    MPG 2024  Ccesa007.pdf
Programacion Anual Matemática5 MPG 2024 Ccesa007.pdf
 
2 REGLAMENTO RM 0912-2024 DE MODALIDADES DE GRADUACIÓN_.pptx
2 REGLAMENTO RM 0912-2024 DE MODALIDADES DE GRADUACIÓN_.pptx2 REGLAMENTO RM 0912-2024 DE MODALIDADES DE GRADUACIÓN_.pptx
2 REGLAMENTO RM 0912-2024 DE MODALIDADES DE GRADUACIÓN_.pptx
 
2024 KIT DE HABILIDADES SOCIOEMOCIONALES.pdf
2024 KIT DE HABILIDADES SOCIOEMOCIONALES.pdf2024 KIT DE HABILIDADES SOCIOEMOCIONALES.pdf
2024 KIT DE HABILIDADES SOCIOEMOCIONALES.pdf
 

SERVLET BASICS

  • 2. Tópicos  Servlet – la gran figura de J2EE  Servlet - modelo request & response  Servlet – ciclo de vida  Servlet – alcance de los objetos  Servlet request  Servlet response: Status, Header, Body  Tratamiento de errores 2
  • 3. Tópicos avanzados:  Session Tracking  Servlet Filters  Eventos del ciclo de vida del servlet  Including, forwarding to, y redirect a otros recursos de la web  Tratamiento de la concurrencia  Invoker Servlet 3
  • 5. Arquitectura J2EE 1.2 An extensible Web technology that uses template data, Java Servlet A Java program that custom elements, scripting languages, and server-side extends the functionality of a Web Java objects to return dynamic content to a client . server, generating dynamic content Typically the template data is HTML or XML elements. and interacting with Web clients The client is often a Web browser. using a request-response paradigm . 5
  • 6. ¿Dónde estan los Servlets y JSP? Web Tier EJB Tier 6
  • 7. ¿Qué es un Servlet?  Objetos Java™ objects que estan basados en un marco de trabajo y APIs los cuales extienden la funcionalidad de un servidor HTTP.  Mapeado a un URL y manejado por el contenedor con una arquitectura simple  Disponible y ejecutable en la gran mayoria de servidores web y servidores de aplicaciones  Independiente de la plataforma y servidor 7
  • 8. Primer código Servlet Public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<title>Hello World!</title>"); } ... } 8
  • 9. Servlet CGI Servlet  Escrito en C, C++,  Escrito en Java Visual Basic y Perl  Poderoso y eficiente  Dificil de mantener, no  Promueve la es escalable, no es escalabilidad, administrable reusabilidad (basado en  Problemas de componentes) seguridad  Construido bajo la  Ineficiente uso de seguridad del lenguaje recursos java  Especifico a la  Independiente de la plataforma y aplicación plataforma y portable 9
  • 10. Servlet vs. CGI Request CGI1 Request CGI1 Child for CGI1 Child for CGI1 Request CGI2 CGI CGI Request CGI2 Based Child for CGI2 Based Child for CGI2 Webserver Webserver Request CGI1 Request CGI1 Child for CGI1 Child for CGI1 Request Servlet1 Request Servlet1 Servlet Based Webserver Servlet Based Webserver Request Servlet2 Servlet1 Servlet1 Request Servlet2 JVM JVM Request Servlet1 Servlet2 Servlet2 10
  • 11. Ventajas de los Servlet  No tiene las limitaciones de los CGI  Muchas herramientas y servidores Web en el mercado soportan Servlet  Acceso a la familia entera de APIs Java  Confiable, mejor performance y escalabilidad  Independiente de la plataforma y servidor  Seguro  Muchos servidores permitir un refresco automatico de servlets por accion administrativa 11
  • 12. ¿Qué es la tecnología JSP?  Permite la separación de lógica de negocio y la presentación − La presentacion es generalmente en la forma de HTML o XML/XSLT − La logica de negocios es implementada como Java Beans o custom tags − Mejor mantenimiento, reusabilidad  Extensible via custom tags  Construido en base a la tecnologia de servlets 12
  • 13. ¿Qué es una pagina JSP?  Un documento basado en texto capaza de retornar contenido dinamico a un browser  Contiene tanto contenido estatico como dinamico − Contenido estatico: HTML, XML − Contenido dinamico: código de programación, y JavaBeans, custom tags 13
  • 14. Código de ejemplo JSP <html> Hello World! <br> <jsp:useBean id="clock" class=“calendar.JspCalendar” /> Today is <ul> <li>Day of month: <%= clock.getDayOfMonth() %> <li>Year: <%= clock.getYear() %> </ul> </html> 14
  • 15. JSP Servlets JSP • Codigo HTML en • Código Java en HTML java • Texto estructurado • Cualquier forma de • Muy facil de construir Data la pagina web para el • No es facil para el autor autor construir una • El codigo es compilado pagina Web en un servlet 15
  • 16. Beneficios JSP  Contenido y logica para mostrar el contenido estan separados  Simplifica el desarrollo con JSP, JavaBeans y custom tags  Soporta la reutilizacion de software a traves de componentes  Se recompila automaticamente cuando los cambios son hechos en el codigo JSP  Facililidad de uso para el autor de paginas web  Independiente de la plataforma 16
  • 17. ¿Cuando usar Servlet vs JSP?  Extender la funcionalidad de un servidor Web para soportar un nuevo formato de archivo  Generar objetos que no contienen HTML como son los graficos (pie charts)  Evitar retornar HTML directamente desde tus servlets el mayor tiempo posible 17
  • 18. ¿Debería yo usar Servlet or JSP?  En la practica, servlet y JSP son usados juntos − via la arquitectura MVC (Model, View, Controller) − Servlet maneja el Controller − JSP maneja el View 18
  • 20. Modelo Servlet Request y Response Servlet Container Request Browser HTTP Request Servlet Response Web Response Server 20
  • 21. ¿Que es lo que hace el Servlet?  Recibe request del cliente(mayormente en la forma de HTTP request)  Extrae cierta informacion del request  Genera contenido o procesa logica de negocio (accesando a base de datos, invocando EJBs, etc)  Crea y envía response al cliente (mayormente en la forma de HTTP) o hace forward del request a otro servlet o pagina JSP 21
  • 22. Requests y Responses  ¿Que es un request? − Informacion que es envia del cliente al servidor  Quien hizo el request  Que data es enviada  Que HTTP Headers son enviados  ¿Que es un response? − Informacion enviada al cliente desde el server  Text(html, plain) o data binaria(image)  HTTP headers, cookies, etc 22
  • 23. HTTP  HTTP request contiene − header − Un metodo  Get: Data de entrada que es pasada como parte de un URL  Post: Data de entrada es pasada dentro del mensaje body  Put  Header − Información del request 23
  • 24. HTTP GET y POST  Son los request del cliente más comunes − HTTP GET & HTTP POST  GET requests: − La informacion ingresada por el usuario es añadida a el URL en un query string − Puede enviar solo una cantidad de data (limitado)  .../servlet/ViewCourse?FirstName=Jose&LastName=Diaz  POST requests: − La informacion es enviada como data(no añadido a un URL) − Puede enviar cualquier cantidad de informacion 24
  • 25. Primer Servlet import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<title>First Servlet</title>"); out.println("<big>Hello Code Camp!</big>"); } } 25
  • 26. Interfaces y Classes de Servlet 26
  • 27. Servlet Interfaces & Classes Servlet GenericServlet HttpSession HttpServlet ServletRequest ServletResponse HttpServletRequest HttpServletResponse 27
  • 28. Ciclo de vida del Servlet 28
  • 29. Ciclo de vida del Servlet Is Servlet Loaded? Http request Load Invoke No Http response Yes Run Servlet Servlet Container Client Server 29
  • 30. Ciclo de vida desde la perspectiva de métodos service( ) init( ) destroy( ) Ready Init parameters doGet( ) doPost( ) Request parameters 30
  • 31. Métodos del Servlet  Invocado por el contenedor − El contenedor controla el ciclo de vida del servlet  Definido en − javax.servlet.GenericServlet class o  init()  destroy()  service() – este es un metodo abstract − javax.servlet.http.HttpServlet class  doGet(), doPost(), doXxx()  service() - implementación 31
  • 32. Métodos del Servlet  init() − Invocado una vez cuando el servlet es instanciado por primera vez − Es idea para configurar algo en este metodo  Configurando a una conección a base de datos  destroy() − Invocado antes que la instancia servlets sea removida − Ideal para liberar recursos  Cerrar una conección a base de datos 32
  • 33. Ejemplo: init() de CatalogServlet.java public class CatalogServlet extends HttpServlet { private BookDB bookDB; // Perform any one-time operation for the servlet, // like getting database connection object. // Note: In this example, database connection object is assumed // to be created via other means (via life cycle event mechanism) // and saved in ServletContext object. This is to share a same // database connection object among multiple servlets. public void init() throws ServletException { bookDB = (BookDB)getServletContext(). getAttribute("bookDB"); if (bookDB == null) throw new UnavailableException("Couldn't get database."); } ... } 33
  • 34. Ejemplo: init() obteniendo parametros de configuración public void init(ServletConfig config) throws ServletException { super.init(config); String driver = getInitParameter("driver"); String fURL = getInitParameter("url"); try { openDBConnection(driver, fURL); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e){ e.printStackTrace(); } } 34
  • 35. Configurando parámetros de inicialización en web.xml <web-app> <servlet> <servlet-name>chart</servlet-name> <servlet-class>ChartServlet</servlet-class> <init-param> <param-name>driver</param-name> <param-value> COM.cloudscape.core.RmiJdbcDriver </param-value> </init-param> <init-param> <param-name>url</param-name> <param-value> jdbc:cloudscape:rmi:CloudscapeDB </param-value> </init-param> </servlet> </web-app> 35
  • 36. Ejemplo: destroy() public class CatalogServlet extends HttpServlet { private BookDB bookDB; public void init() throws ServletException { bookDB = (BookDB)getServletContext(). getAttribute("bookDB"); if (bookDB == null) throw new UnavailableException("Couldn't get database."); } public void destroy() { bookDB = null; } ... } 36
  • 37. Métodos del Servlet  service() javax.servlet.GenericServlet class − Método abstracto  service() in javax.servlet.http.HttpServlet class − Metodo concreto(implementación) − Delega a doGet(), doPost(), etc − No sobreescribir este metodo  doGet(), doPost(), doXxx() en javax.servlet.http.HttpServlet − Maneja HTTP GET, POST, etc. requests − Sobreescribe estos metodos en tu servlet para darle un comportamiento particular 37
  • 38. service() & doGet()/doPost()  El método service() toma requests y responses genericos: − service(ServletRequest request, ServletResponse response)  doGet() o doPost() toman HTTP requests y responses: − doGet(HttpServletRequest request, HttpServletResponse response) − doPost(HttpServletRequest request, HttpServletResponse response) 38
  • 39. Service() Method GenericServlet Server subclass Subclass of Request GenericServlet class Service( ) Response Key: Implemented by subclass 39
  • 40. Métodos doGet() y doPost() Server HttpServlet subclass doGet( ) Request Service( ) Response doPost( ) Key: Implemented by subclass 40
  • 41. Tareas que tu haces en doGet() & doPost()  Extraes informacion enviada del cliente(parametro HTTP) desde el HTTP request  Set (Save) y get (read) atributos en/desde objetos segun el scope (request, session)  Ejecutar logica de negocios o acceso a base de datos  Opcionalmente hacer forward del request a otro recurso Web u otros componentes Web (Servlet o JSP)  Completar mensajes HTTP response y enviar este a el cliente 41
  • 42. Ejemplo: Simple doGet() import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Just send back a simple HTTP response response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<title>First Servlet</title>"); out.println("<big>Hello J2EE Programmers! </big>"); } } 42
  • 43. Ejemplo: doGet() Sofisticado public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Read session-scope attribute “message” HttpSession session = request.getSession(true); ResourceBundle messages = (ResourceBundle)session.getAttribute("messages"); // Set headers and buffer size before accessing the Writer response.setContentType("text/html"); response.setBufferSize(8192); PrintWriter out = response.getWriter(); // Then write the response (Populate the header part of the response) out.println("<html>" + "<head><title>" + messages.getString("TitleBookDescription") + "</title></head>"); // Get the dispatcher; it gets the banner to the user RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner"); if (dispatcher != null) dispatcher.include(request, response); 43
  • 44. Ejemplo: doGet() Sofisticado // Get the identifier of the book to display (Get HTTP parameter) String bookId = request.getParameter("bookId"); if (bookId != null) { // and the information about the book (Perform business logic) try { BookDetails bd = bookDB.getBookDetails(bookId); Currency c = (Currency)session.getAttribute("currency"); if (c == null) { c = new Currency(); c.setLocale(request.getLocale()); session.setAttribute("currency", c); } c.setAmount(bd.getPrice()); // Print out the information obtained out.println("..."); } catch (BookNotFoundException ex) { response.resetBuffer(); throw new ServletException(ex); } } out.println("</body></html>"); out.close(); } 44
  • 45. Pasos para completar HTTP Response  Llenar Response headers  Establecer algunas propiedades del response − Buffer size  Obtener un objeto output stream desde el response  Escribir el contenido a dicho output stream 45
  • 46. Ejemplo: Simple Response Public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Fill response headers response.setContentType("text/html"); // Set buffer size response.setBufferSize(8192); // Get an output stream object from the response PrintWriter out = response.getWriter(); // Write body content to output stream out.println("<title>First Servlet</title>"); out.println("<big>Hello J2EE Programmers! </big>"); } } 46
  • 48. Scope Objects  Permite compartir información a traves de componentes web via atributos mantenidos en estos Scope objects − Atributos son pares de la forma nombre/objeto  Atributos mantenidos en estos Scope objets son accesado a traves de − getAttribute() & setAttribute()  4 Scope objects son definidos − Contexto web, session, request, page 48
  • 49. Cuatro Scope Objects: Accesibilidad  Contexto Web(ServletContext) − Accesible desde componentes Web que estan dentro de un contexto  Session − Accesible desde componentes web que manejan un request que pertenece a la session  Request − Accesible desde componentes web que manejan el request  Page − Accesible desde paginas JSP que han creado el objeto 49
  • 50. Cuatro Scope Objects: Class  Web context − javax.servlet.ServletContext  Session − javax.servlet.http.HttpSession  Request − Subtipo de javax.servlet.ServletRequest: javax.servlet.http.HttpServletRequest  Page − javax.servlet.jsp.PageContext 50
  • 52. ¿Para que es un ServletContext ?  Usado por servlets para − Establecer (Set) y obtener (get) objetos de scope context (o application) y obtener el valor de sus atributos − Obtener un request dispatcher  Para hacer forward o incluir un componente web − Accesar a parametros de inicializacion del contexto web establecidos en el web.xml − Accesar a recursos Web asociados con el contexto Web − Log − Accesar a otra informacion miscelanea 52
  • 53. Scope de ServletContext  El scope o alcance es − Compartido por todos los servlets y paginas JSP dentro de una “aplicación web"  Esto es el porque de ser llamado “scope application” − Una “aplicación web" es una colección de servlets y contenido instalado bajo un subconjunto especifico de URL namespaces y posiblemente instalado via un *.war  Todos los servlets en la aplicación web BookStore comparten el mismo objeto ServletContext − Hay un objeto ServletContext por “aplicación web" y por Java virtual machine 53
  • 54. ServletContext: Web Application Scope Client 1 ServletContext server application Client 2 54
  • 55. ¿Como accesar al objeto ServletContext?  Dentro de tu codigo usando getServletContext()  Dentro del codigo de un filtro de servlet, llamando a, getServletContext()  El ServletContext es contenido en el objeto ServletConfig, el cual es provisto por el web server a un servlet cuando este es inicializado − init (ServletConfig servletConfig) en la interface Servlet 55
  • 56. Ejemplo: Obteniendo Attribute Value de ServletContext public class CatalogServlet extends HttpServlet { private BookDB bookDB; public void init() throws ServletException { // Get context-wide attribute value from // ServletContext object bookDB = (BookDB)getServletContext(). getAttribute("bookDB"); if (bookDB == null) throw new UnavailableException("Couldn't get database."); } } 56
  • 57. Ejemplo: Obteniendo y usando el objeto RequestDispatcher public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); ResourceBundle messages = (ResourceBundle)session.getAttribute("messages"); // set headers and buffer size before accessing the Writer response.setContentType("text/html"); response.setBufferSize(8192); PrintWriter out = response.getWriter(); // then write the response out.println("<html>" + "<head><title>" + messages.getString("TitleBookDescription") + "</title></head>"); // Get the dispatcher; it gets the banner to the user RequestDispatcher dispatcher = session.getServletContext().getRequestDispatcher("/banner"); if (dispatcher != null) dispatcher.include(request, response); ... 57
  • 58. Ejemplo: Logging public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... getServletContext().log(“Life is good!”); ... getServletContext().log(“Life is bad!”, someException); 58
  • 60. ¿Porqué HttpSession?  Necesidad de un medio para mantener información del cliente a traves de una serie de request desde el mismo usuario (u originado desde el mismo browser) en un periodo de tiempo − Ejemplo: Online shopping cart  HttpSession mantiene el estado del cliente − Usado por Servlets para establecer y obtener los valores de atributos del session scope 60
  • 61. ¿Como obtener HttpSession?  via el metodo getSession() del objeto Request (HttpServletRequest) 61
  • 62. Ejemplo: HttpSession public class CashierServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart)session.getAttribute("cart"); ... // Determine the total price of the user's books double total = cart.getTotal(); 62
  • 64. ¿Qué es Servlet Request?  Contiene información pasada del cliente a el servlet  Todos los servlet requests implementan la interface ServletRequest el cual define metodos para accesar a − Parametros enviados por el Cliente − Atributos nombre/objeto − Localidades − Cliente y servidor − Input stream − Información del protocolo − Content type − Si el request ha sido hecho de una conexión segura (HTTPS) 64
  • 65. Requests data, client, server, header servlet itself Request Servlet 1 Servlet 2 Response Servlet 3 Web Server 65
  • 66. Obteniendo parametros enviados por el cliente  Un request puede venir con cualquier numero de parametros enviados por el cliente  Los parametros son enviados de dos formas: − GET: como un query string, añadido a un URL − POST: como data POST codificada, no aparece en el URL  getParameter("paraName") − Retorna el valor de paraName − Retorna null si el parametro no esta presente − Trabaja indenticamente para request GET y POST 66
  • 67. Un ejemplo de Formulario usando GET <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Collecting Three Parameters</TITLE> </HEAD> <BODY BGCOLOR="#FDF5E6"> <H1 ALIGN="CENTER">Please Enter Your Information</H1> <FORM ACTION="/sample/servlet/ThreeParams"> First Name: <INPUT TYPE="TEXT" NAME="param1"><BR> Last Name: <INPUT TYPE="TEXT" NAME="param2"><BR> Class Name: <INPUT TYPE="TEXT" NAME="param3"><BR> <CENTER> <INPUT TYPE="SUBMIT"> </CENTER> </FORM> </BODY> </HTML> 67
  • 69. El servlet: Get import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Simple servlet that reads three parameters from the html form */ public class ThreeParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Your Information"; out.println("<HTML>" + "<BODY BGCOLOR="#FDF5E6">n" + "<H1 ALIGN=CENTER>" + title + "</H1>n" + "<UL>n" + " <LI><B>First Name in Response</B>: " + request.getParameter("param1") + "n" + " <LI><B>Last Name in Response</B>: " + request.getParameter("param2") + "n" + " <LI><B>NickName in Response</B>: " + request.getParameter("param3") + "n" + "</UL>n" + "</BODY></HTML>"); } } 69
  • 70. Un formulario usando POST <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>A Sample FORM using POST</TITLE> </HEAD> <BODY BGCOLOR="#FDF5E6"> <H1 ALIGN="CENTER">A Sample FORM using POST</H1> <FORM ACTION="/sample/servlet/ShowParameters" METHOD="POST"> Item Number: <INPUT TYPE="TEXT" NAME="itemNum"><BR> Quantity: <INPUT TYPE="TEXT" NAME="quantity"><BR> Price Each: <INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR> First Name: <INPUT TYPE="TEXT" NAME="firstName"><BR> <TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR> Credit Card Number: <INPUT TYPE="PASSWORD" NAME="cardNum"><BR> <CENTER> <INPUT TYPE="SUBMIT" VALUE="Submit Order"> </CENTER> </FORM> </BODY> </HTML> 70
  • 72. Servlet: POST import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShowParameters extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } 72
  • 73. Quien establece atributos Object/ value  Request attributes pueden ser establecidos en dos formas − El contenedor de servlets por si mismo establece atributos para hacer disponible esta información acerca de un request  Ejemplo: atributo javax.servlet.request.X509Certificate para HTTPS − Establecido por codigo asi  void setAttribute(java.lang.String name, java.lang.Object o)  Embebido en un request antes de ser llamado un RequestDispatcher 73
  • 74. Obteniendo información Local public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); ResourceBundle messages = (ResourceBundle)session.getAttribute("messages"); if (messages == null) { Locale locale=request.getLocale(); messages = ResourceBundle.getBundle( "messages.BookstoreMessages", locale); session.setAttribute("messages", messages); } 74
  • 75. Obteniendo información del Cliente  El Servlet puede obtener información del cliente − String request.getRemoteAddr()  Obtiene IP Address − String request.getRemoteHost()  Obtiene nombre del cliente 75
  • 76. Obteniendo información del server  El Servlet puede obtener información del servidor: − String request.getServerName()  e.g. "www.sun.com" − int request.getServerPort()  e.g. Port number "8080" 76
  • 77. Obteniendo información Misc.  Input stream − ServletInputStream getInputStream() − java.io.BufferedReader getReader()  Protocol − java.lang.String getProtocol()  Content type − java.lang.String getContentType()  Es seguro o no(if it is HTTPS or not) − boolean isSecure() 77
  • 79. ¿Qué es HTTP Servlet Request?  Contiene data pasada del cliente HTTP a el servlet HTTP  Creado por contenedor de servlets y pasado al servlet como parametros de los metodos doGet() o doPost()  HttpServletRequest es una extension de ServletRequest y provee metodos adicionales para accesar a − HTTP request URL  Context, servlet, path, query information − Misc. HTTP Request header information − Authentication type & User security information − Cookies − Session 79
  • 80. HTTP Request URL  Contiene las siguientes partes − http://[host]:[port]/[request path]?[query string] 80
  • 81. HTTP Request URL: [request path]  http://[host]:[port]/[request path]?[query string]  [request path] es hecho de − Context: /<contexto de la aplicación web> − Servlet name: /<component alias> − Path information: el resto  Ejemplos − http://localhost:8080/hello1/greeting − http://localhost:8080/hello1/greeting.jsp − http://daydreamer/catalog/lawn/index.html 81
  • 82. HTTP Request URL: [query string]  http://[host]:[port]/[request path]?[query string]  [query string] son compuestos por un conjunto de parametros y valores que el usuario ingreso  Dos maneras de crear query strings − Un query string pued aparecer explicitamente en una pagina web  <a href="/bookstore1/catalog?Add=101">Add To Cart</a>  String bookId = request.getParameter("Add"); − Un query string es añadido a un URL cuando un formulario es submiteado usando el metodo GET HTTP  http://localhost/hello1/greeting?username=Monica+Clinton  String userName=request.getParameter(“username”) 82
  • 83. Context, Path, Query, Parameter Methods  String getContextPath()  String getQueryString()  String getPathInfo()  String getPathTranslated() 83
  • 84. HTTP Request Headers  HTTP requests incluyen headers los cuales proveen información extra acerca del request  Ejemplo de HTTP 1.1 Request: GET /search? keywords= servlets+ jsp HTTP/ 1.1 Accept: image/ gif, image/ jpg, */* Accept-Encoding: gzip Connection: Keep- Alive Cookie: userID= id456578 Host: www.sun.com Referer: http:/www.sun.com/codecamp.html User-Agent: Mozilla/ 4.7 [en] (Win98; U) 84
  • 85. HTTP Request Headers  Accept − Indica los tipos MIME que el browser puede manejar  Accept-Encoding − Indica encoding(e. g., gzip or compress) que el browser puede manejar  Authorization − Identificación del usuario para paginas protegidas − En lugar de HTTP authorization, usa HTML forms para enviar username/password y almacenar la informacion en un objeto session 85
  • 86. HTTP Request Headers  Connection − En HTTP 1.1, la conexión persistentes es por defecto − Servlets deben de configurar Content-Length con setContentLength (usar ByteArrayOutputStream para determinar longitud de salida) para soportar conexiones persistentes  Cookie − Usar getCookies, no getHeader  Host − Indica host dado en URL original. − Esto es requerido en HTTP 1.1. 86
  • 87. HTTP Request Headers  If-Modified-Since − Indica que cliente desea la pagina solo si esta ha sido modificada desde la ultima fecha especificada. − No manejar esta situacion directamente; implementar en su lugar getLastModified.  Referer − URL de paginas web referidas. − Util para seguimiento de trafico  User-Agent − String identifa el browser que esta haciendo el request. − Usar con extrema precaución! 87
  • 88. HTTP Header Methods  String getHeader(java.lang.String name) − Valor del request header como String  java.util.Enumeration getHeaders(java.lang.String name) − Valores del request header especificado  java.util.Enumeration getHeaderNames() − Nombres de los request headers  int getIntHeader(java.lang.String name) − valor del request header especificado como int 88
  • 89. Mostrando Request Headers //Shows all the request headers sent on this particular request. public class ShowRequestHeaders extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Servlet Example: Showing Request Headers"; out.println("<HTML>" + ... "<B>Request Method: </B>" + request.getMethod() + "<BR>n" + "<B>Request URI: </B>" + request.getRequestURI() + "<BR>n" + "<B>Request Protocol: </B>" + request.getProtocol() + "<BR><BR>n" + ... "<TH>Header Name<TH>Header Value"); Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName = (String)headerNames.nextElement(); out.println("<TR><TD>" + headerName); out.println(" <TD>" + request.getHeader(headerName)); } ... } } 89
  • 90. Request Headers - Ejemplo 90
  • 91. Authentication & User Security Information  String getRemoteUser() − Nombre del usuario si el servlet ha sido protegido por password, null en caso contrario  String getAuthType() − Nombre del esquema de autenticación usado para proteger el servlet  boolean isUserInRole(java.lang.String role) − ¿Esta el usuario incluido en role especificado?  String getRemoteUser() − Login del usuario que esta haciendo el request, si el usuario ha sido autenticado, null en caso contrario. 91
  • 92. Cookie Method (in HTTPServletRequest)  Cookie[] getCookies() − Un array conteniendo todos los objetos Cookie que el ciente envia con el request 92
  • 94. ¿Qué es Servlet Response?  Contiene data pasada del servlet a el cliente  Todos los servlet responses implementan la interface ServletResponse − Recupera un output stream − Indica content type − Indica el buffer output − Set información de localización  HttpServletResponse extends ServletResponse − HTTP response status code − Cookies 94
  • 95. Responses Request Servlet 1 Response Structure: Servlet 2 status code , headers and body. Response Servlet 3 Web Server 95
  • 96. Response Structure Status Code Response Headers Response Body 96
  • 97. Status Code in Http Response 97
  • 98. HTTP Response Status Codes  ¿Porqué nosotros necesitamos HTTP response status code? − Para hacer Forward a otra pagina − Indicar si el recurso esta faltando − Instruir al browser para usar copiado de informacion por cache 98
  • 99. Metodos para establecer HTTP Response Status Codes  public void setStatus(int statusCode) − Status codes son definidos en HttpServletResponse − Status codes son numero organizados en cinco categorías  100-199 Informational  200-299 Successful  300-399 Redirection  400-499 Incomplete  500-599 Server Error − El codigo por defecto es 200 (OK) 99
  • 100. Ejemplo de HTTP Response Status HTTP/ 1.1 200 OK Content-Type: text/ html <! DOCTYPE ...> <HTML ... </ HTML> 100
  • 101. Status Codes comunes  200 (SC_OK) − Success − Default para servlets  204 (SC_No_CONTENT) − Success pero sin body response − El Browser deberia mantener mostrando el contenido previo  301 (SC_MOVED_PERMANENTLY) − El documento fue movido permanentemente (indicado en Location header) − El browser ira a una nueva ubicacion automaticamente 101
  • 102. Status Codes Comunes  302 (SC_MOVED_TEMPORARILY) − El mensaje es "Found" − El documento es movido temporalmente o caso contrario (indicado en Location header) − Browsers van a una nueva ubicacion automaticamente − Servlets deberian usar sendRedirect, no setStatus, cuando establecen este header  401 (SC_UNAUTHORIZED) − El browser trato de acceder a una pagina protegida sin la autorizacion correspondiente  404 (SC_NOT_FOUND) − Pagina no encontrada 102
  • 103. Metodos para enviar Error  Error status codes (400-599) pueden ser usados en los metodos sendError  public void sendError(int sc) − El servidor puede dar el especial tratamiento del error  public void sendError(int code, String message) − Wrapea el mensaje dentro de un pequeño documento HTML 103
  • 104. setStatus() & sendError() try { returnAFile(fileName, out) } catch (FileNotFoundException e) { response.setStatus(response.SC_NOT_FOUND); out.println("Response body"); } has same effect as try { returnAFile(fileName, out) } catch (FileNotFoundException e) { response.sendError(response.SC_NOT_FOUND); } 104
  • 106. ¿Porqué HTTP Response Headers?  Dar forwarding location  Especificar cookies  Proveer la fecha de modificacion de la pagina  Instruir al browser para recargar la pagina despues de un periodo de tiempo  Dar el tamaño del archivo de manera que la conexión persistente HTTP pueda ser usada  Diseñar el tipo de documento que esta siendo generado  Etc. 106
  • 107. Metodos para establecer Arbitrariamente Response Headers  public void setHeader( String headerName, String headerValue) − Establece un header.  public void setDateHeader( String name, long millisecs) − Convierte milisegundos desde 1970 a un date string enformato GMT  public void setIntHeader( String name, int headerValue) − Prevee la necesidad de convertir int a String antes de llamar a setHeader  addHeader, addDateHeader, addIntHeader − Añade nuevas ocurrencias de header en lugar de reemplazarlos 107
  • 108. Metodos para establecer Response Headers comunes  setContentType − Establece el contenido- tipo de header. Servlets casi siempre usan este.  setContentLength − Establece la longitud del content header. Usado para conexiones persistentes HTTP.  addCookie − Añade un valor a el Set- Cookie header.  sendRedirect − Estable el Location header y cambia status code 108
  • 109. HTTP 1.1 Response Headers comunes  Location − Especifica una nueva location del documento − Usar sendRedirect en lugar de establecer este directamente  Refresh − Especifica un delay antes de que el browser automaticamente recargue la pagina  Set-Cookie − Los cookies que el browser debe recordar. No establecer este header automaticamente. − Usar addCookie en su lugar. 109
  • 110. continua  Cache-Control (1.1) y Pragma (1.0) − Un no-cache valor previene al browser de poner la pagina en cache. Envia ambos headers o chequea la version de HTTP.  Content- Encoding − La manera en que el documento es codificado. El Browser revierte esta codificacion antes de manejar el documento  Content- Length − El numero de bytes en el response. Usado para conexiones persistentes HTTP 110
  • 111. Continua  Content- Type − El MIME type del documento que esta siendo retornado. − Usa setContentType para establecer este header.  Ultima modificación − La ultima vez que el documento fue cambiado − No establecer este header explicitamente. − Proveer un metodo getLastModified en su lugar. 111
  • 112. Ejemplo de codigo - Refresh public class DateRefresh extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); res.setHeader("Refresh", "5"); out.println(new Date().toString()); } } 112
  • 114. Escribiendo un Response Body  Un servlet casi siempre retorna un response body  Response body puede ser un PrintWriter o un ServletOutputStream  PrintWriter − Usando response.getWriter() − Para salida basada en caracteres  ServletOutputStream − Usando response.getOutputStream() − Para data binaria (imagenes) 114
  • 116. Manejando Errores  El contenedor web genera una pagina de error por defecto  Tu puedes proporcionar tu propia pagina de error  Pasos para manejar errores − Crea paginas de error html apropiados para condiciones de error − Modificar el web.xml 116
  • 117. Ejemplo: Establecer paginas de error en web.xml <error-page> <exception-type> exception.BookNotFoundException </exception-type> <location>/errorpage1.html</location> </error-page> <error-page> <exception-type> exception.BooksNotFoundException </exception-type> <location>/errorpage2.html</location> </error-page> <error-page> <exception-type>exception.OrderException</exception-type> <location>/errorpage3.html</location> </error-page> 117
  • 118. ¡Gracias! 118