SlideShare uma empresa Scribd logo
1 de 7
Baixar para ler offline
Servlets que manejan datos de formularios HTML

Formulario HTML que solicita el ingreso del nombre y clave de un usuario.
Posteriormente se recuperan los dos parámetros en un servlet y se muestran
en otra página generada por el servlet.




formulario.html

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Formulario HTML</title>
</head>
<body>
        <form method="post" action="ServletRecolector">
                <p>Nombre de usuario: <input type="text" name="usuario" size="20" /></p>
                <p>Clave: <input type="password" name="clave" size="20" /></p>
                <p><input type="submit" value="confirmar" /></p>
        </form>
</body>

</html>
Codificamos la página html con el formulario web que solicita el ingreso del
nombre de usuario y su clave…

En la propiedad action de la etiqueta form indicamos el nombre del servlet
que recuperará los datos del formulario…

<form method="post" action="ServletRecolector">



ServletRecolector.java

package pkgServForm;

import   java.io.IOException;
import   java.io.PrintWriter;
import   javax.servlet.ServletException;
import   javax.servlet.annotation.WebServlet;
import   javax.servlet.http.HttpServlet;
import   javax.servlet.http.HttpServletRequest;
import   javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletRecolector
 */
@WebServlet("/ServletRecolector")
public class ServletRecolector extends HttpServlet {
        private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletRecolector() {
        super();
        // TODO Auto-generated constructor stub
    }

        /**
          * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
          */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
                 // TODO Auto-generated method stub
        }

        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
                // TODO Auto-generated method stub

          PrintWriter out = response.getWriter();

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

          out.println("Usuario:"); out.println(request.getParameter("usuario"));
          out.println("<br/>Clave:"); out.println(request.getParameter("clave"));

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

          }

}
En la clase ServletRecolector implementamos todo el código en el método
doPost, ya que este se ejecuta cuando se envían los datos de un formulario
HTML mediante post:

<form method="post" action="ServletRecolector">


Para recuperar los datos de los controles text y password del formulario HTML
el objeto request de la clase HttpServletRequest dispone de un método llamado
getParamenter indicándole el nombre del control a recuperar:

          request.getParameter("usuario");
          request.getParameter("clave");


Del objeto response de la clase HttpServletResponse obtenemos un objeto
PrintWriter (mediante su método getWriter) usado para enviar la salida de
vuelta al cliente (navegador).


PrintWriter out = response.getWriter();
out.println(request.getParameter("clave"));



Resultado de la ejecución…
Ejemplo02: Servlet que maneja parámetros enviados por POST desde un form que
contiene controles de tipo select (cuadro combinado), text (caja de texto),
checkbox (se pueden marcar varias opciones), radio (excluyente, sólo se puede
seleccionar una opción).

El resultado de la ejecución sería…




El servlet recupera los parámetros enviados desde el form y los muestra en
otra página html que envía al cliente.




Estructura de directorios y archivos en el proyecto web dinámico en Eclipse.
formulario02.html

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>

          <form method="post" action="ServletRecolector">
                  <p>Title: <select size="1" name="title">
                          <option selected="selected">Mr</option>
                          <option>Mrs</option>
                          <option>Miss</option>
                          <option>Ms</option>
                          <option>Other</option>
                  </select></p>

                    <p>Name: <input type="text" name="name" size="20" value="---"/></p>
                    <p>City: <input type="text" name="city" size="20" value="---"/></p>
                    <p>Country: <input type="text" name="country" size="20" value="---"/></p>
                    <p>Telephone: <input type="text" name="tel" size="20" value="---"/></p>

                    <p>Please inform us of   your interests:</p>
                    <input type="checkbox"   name="interests" value="Sport"/>Sport<br/>
                    <input type="checkbox"   name="interests" value="Music"/>Music<br/>
                    <input type="checkbox"   name="interests" value="Reading"/>Reading<br/>
                    <input type="checkbox"   name="interests" value="TV and Film"/>TV and Film

                <p>Your age: <input type="radio" name="age" value="25orless"
checked="checked"/>Less than 25
                <input type="radio" name="age" value="26to40"/>26-40
                <input type="radio" name="age" value="41to65"/>41-65
                <input type="radio" name="age" value="over65"/>Over 65</p>
                <p><input type="submit" value="Submit"/></p>

          </form>

</body>
</html>
ServletRecolector.java

package pkgServletForm;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServletRecolector
 */
@WebServlet("/ServletRecolector")
public class ServletRecolector extends HttpServlet {
        private static final long serialVersionUID = 1L;

        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
                // TODO Auto-generated method stub

            ServletOutputStream out = response.getOutputStream();
            response.setContentType("text/html");
            out.println("<html><head><title>Basic Form Processor Output</title></head>");
            out.println("<body>");
            out.println("<h1>Here is your Form Data</h1>");

            //Opción elegida en el cuadro combinado (tratamiento)
            out.println("Your title is " + request.getParameter("title"));

            //Parámetros nombre, ciudad, pais y teléfono (individuales text)
            out.println("<br>Your name is " + request.getParameter("name"));
            out.println("<br>Your city is " + request.getParameter("city"));
            out.println("<br>Your country is " + request.getParameter("country"));
            out.println("<br>Your tel is " + request.getParameter("tel"));


            // extracting data from the checkbox field (checkbox intereses)
            String[] interests = request.getParameterValues("interests");
            if(interests!=null){
                out.println("</br>Your interests include<ul> ");
                    for (int i=0;i<interests.length; i++) {
                        out.println("<li>" + interests[i]);
                    }
                    out.println("</ul>");
            }else{
                out.println("<p>No tiene aficiones...</p>");
            }

            //Opción elegida (edad radio)
            out.println("<br>Your age is "   + request.getParameter("age"));
            out.println("</body></html>");

        }
}
getParameterValues

public java.lang.String[] getParameterValues(java.lang.String name)
       Returns an array of String objects containing all of the values the
       given request parameter has, or null if the parameter does not exist.

      If the parameter has a single value, the array has a length of 1.

      Parameters:
      name - a String containing the name of the parameter whose value is
      requested
      Returns:
      an array of String objects containing the parameter's values



getParameter

public java.lang.String getParameter(java.lang.String name)
       Returns the value of a request parameter as a String, or null if the
       parameter does not exist. Request parameters are extra information
       sent with the request. For HTTP servlets, parameters are contained in
       the query string or posted form data.

      You should only use this method when you are sure the parameter has
      only one value. If the parameter might have more than one value, use
      getParameterValues(java.lang.String).

      If you use this method with a multivalued parameter, the value
      returned is equal to the first value in the array returned by
      getParameterValues.

      If the parameter data was sent in the request body, such as occurs
      with an HTTP POST request, then reading the body directly via
      getInputStream() or getReader() can interfere with the execution of
      this method.

      Parameters:
      name - a String specifying the name of the parameter
      Returns:
      a String representing the single value of the parameter

Mais conteúdo relacionado

Mais procurados (20)

Java web application development
Java web application developmentJava web application development
Java web application development
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
ASP.NET WEB API
ASP.NET WEB APIASP.NET WEB API
ASP.NET WEB API
 
Clases Genéricas en Java
Clases Genéricas en JavaClases Genéricas en Java
Clases Genéricas en Java
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
 
Dataset y datatable
Dataset y datatableDataset y datatable
Dataset y datatable
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Advanced java programming-contents
Advanced java programming-contentsAdvanced java programming-contents
Advanced java programming-contents
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Ejercicio sql tienda informatica (1)
Ejercicio sql tienda informatica (1)Ejercicio sql tienda informatica (1)
Ejercicio sql tienda informatica (1)
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Java exception-handling
Java exception-handlingJava exception-handling
Java exception-handling
 
Comandos ddl
Comandos ddlComandos ddl
Comandos ddl
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
Enterprise java unit-2_chapter-2
Enterprise  java unit-2_chapter-2Enterprise  java unit-2_chapter-2
Enterprise java unit-2_chapter-2
 

Destaque

Servlet Hola Mundo con Eclipse y Tomcat
Servlet Hola Mundo con Eclipse y TomcatServlet Hola Mundo con Eclipse y Tomcat
Servlet Hola Mundo con Eclipse y Tomcatjubacalo
 
Java::Acceso a Bases de Datos
Java::Acceso a Bases de DatosJava::Acceso a Bases de Datos
Java::Acceso a Bases de Datosjubacalo
 
Java AWT Calculadora
Java AWT CalculadoraJava AWT Calculadora
Java AWT Calculadorajubacalo
 
Java Thread Cronometro
Java Thread CronometroJava Thread Cronometro
Java Thread Cronometrojubacalo
 
Acceso a BBDD mediante un servlet
Acceso a BBDD mediante un servletAcceso a BBDD mediante un servlet
Acceso a BBDD mediante un servletjubacalo
 
Sincronizar Threads
Sincronizar ThreadsSincronizar Threads
Sincronizar Threadsjubacalo
 
jQuery Mobile :: Cuadros de diálogo
jQuery Mobile :: Cuadros de diálogojQuery Mobile :: Cuadros de diálogo
jQuery Mobile :: Cuadros de diálogojubacalo
 
Find File Servlet DB
Find File Servlet DBFind File Servlet DB
Find File Servlet DBjubacalo
 
Acciones JSP
Acciones JSPAcciones JSP
Acciones JSPjubacalo
 
Jsp directiva page
Jsp directiva pageJsp directiva page
Jsp directiva pagejubacalo
 
Explicación del código del Servlet HolaMundo
Explicación del código del Servlet HolaMundoExplicación del código del Servlet HolaMundo
Explicación del código del Servlet HolaMundojubacalo
 
Proyecto JSP
Proyecto JSPProyecto JSP
Proyecto JSPjubacalo
 
Elementos de script en JSP
Elementos de script en JSPElementos de script en JSP
Elementos de script en JSPjubacalo
 
Java AWT Tres en Raya
Java AWT Tres en RayaJava AWT Tres en Raya
Java AWT Tres en Rayajubacalo
 
Java Applet:::Pelota que rebota en un recinto.
Java Applet:::Pelota que rebota en un recinto.Java Applet:::Pelota que rebota en un recinto.
Java Applet:::Pelota que rebota en un recinto.jubacalo
 
Programa Java que gestiona los productos que comercializan varios viveros
Programa Java que gestiona los productos que comercializan varios viverosPrograma Java que gestiona los productos que comercializan varios viveros
Programa Java que gestiona los productos que comercializan varios viverosjubacalo
 
Java ArrayList Iterator
Java ArrayList IteratorJava ArrayList Iterator
Java ArrayList Iteratorjubacalo
 
Java HashMap
Java HashMapJava HashMap
Java HashMapjubacalo
 
jQuery Mobile :: Enlaces a páginas internas.
jQuery Mobile :: Enlaces a páginas internas.jQuery Mobile :: Enlaces a páginas internas.
jQuery Mobile :: Enlaces a páginas internas.jubacalo
 
Práctica Completa en Flash – ActionScript
Práctica Completa en Flash – ActionScriptPráctica Completa en Flash – ActionScript
Práctica Completa en Flash – ActionScriptjubacalo
 

Destaque (20)

Servlet Hola Mundo con Eclipse y Tomcat
Servlet Hola Mundo con Eclipse y TomcatServlet Hola Mundo con Eclipse y Tomcat
Servlet Hola Mundo con Eclipse y Tomcat
 
Java::Acceso a Bases de Datos
Java::Acceso a Bases de DatosJava::Acceso a Bases de Datos
Java::Acceso a Bases de Datos
 
Java AWT Calculadora
Java AWT CalculadoraJava AWT Calculadora
Java AWT Calculadora
 
Java Thread Cronometro
Java Thread CronometroJava Thread Cronometro
Java Thread Cronometro
 
Acceso a BBDD mediante un servlet
Acceso a BBDD mediante un servletAcceso a BBDD mediante un servlet
Acceso a BBDD mediante un servlet
 
Sincronizar Threads
Sincronizar ThreadsSincronizar Threads
Sincronizar Threads
 
jQuery Mobile :: Cuadros de diálogo
jQuery Mobile :: Cuadros de diálogojQuery Mobile :: Cuadros de diálogo
jQuery Mobile :: Cuadros de diálogo
 
Find File Servlet DB
Find File Servlet DBFind File Servlet DB
Find File Servlet DB
 
Acciones JSP
Acciones JSPAcciones JSP
Acciones JSP
 
Jsp directiva page
Jsp directiva pageJsp directiva page
Jsp directiva page
 
Explicación del código del Servlet HolaMundo
Explicación del código del Servlet HolaMundoExplicación del código del Servlet HolaMundo
Explicación del código del Servlet HolaMundo
 
Proyecto JSP
Proyecto JSPProyecto JSP
Proyecto JSP
 
Elementos de script en JSP
Elementos de script en JSPElementos de script en JSP
Elementos de script en JSP
 
Java AWT Tres en Raya
Java AWT Tres en RayaJava AWT Tres en Raya
Java AWT Tres en Raya
 
Java Applet:::Pelota que rebota en un recinto.
Java Applet:::Pelota que rebota en un recinto.Java Applet:::Pelota que rebota en un recinto.
Java Applet:::Pelota que rebota en un recinto.
 
Programa Java que gestiona los productos que comercializan varios viveros
Programa Java que gestiona los productos que comercializan varios viverosPrograma Java que gestiona los productos que comercializan varios viveros
Programa Java que gestiona los productos que comercializan varios viveros
 
Java ArrayList Iterator
Java ArrayList IteratorJava ArrayList Iterator
Java ArrayList Iterator
 
Java HashMap
Java HashMapJava HashMap
Java HashMap
 
jQuery Mobile :: Enlaces a páginas internas.
jQuery Mobile :: Enlaces a páginas internas.jQuery Mobile :: Enlaces a páginas internas.
jQuery Mobile :: Enlaces a páginas internas.
 
Práctica Completa en Flash – ActionScript
Práctica Completa en Flash – ActionScriptPráctica Completa en Flash – ActionScript
Práctica Completa en Flash – ActionScript
 

Semelhante a Servlets que manejan datos de formularios HTML

Tema 6 - Formularios en html
Tema 6 - Formularios en htmlTema 6 - Formularios en html
Tema 6 - Formularios en htmlPamela Rodriguez
 
Php excel
Php excelPhp excel
Php excelpcuseth
 
Programación web con JSP
Programación web con JSPProgramación web con JSP
Programación web con JSPousli07
 
Practica utilizacion de beans en jsp
Practica  utilizacion de beans en jspPractica  utilizacion de beans en jsp
Practica utilizacion de beans en jspBoris Salleg
 
Peticiones y respuestas
Peticiones y respuestasPeticiones y respuestas
Peticiones y respuestasEdwin Enriquez
 
Guia N5 Proyectos Web Consultas Php Y My Sql
Guia N5   Proyectos Web   Consultas Php Y My SqlGuia N5   Proyectos Web   Consultas Php Y My Sql
Guia N5 Proyectos Web Consultas Php Y My SqlJose Ponce
 
Bases de Datos en Java - Intro a JDBC
Bases de Datos en Java - Intro a JDBCBases de Datos en Java - Intro a JDBC
Bases de Datos en Java - Intro a JDBCCarlos Hernando
 
Screen scraping
Screen scrapingScreen scraping
Screen scrapingThirdWay
 
CSA - Web Parts en SharePoint 2010
CSA - Web Parts en SharePoint 2010CSA - Web Parts en SharePoint 2010
CSA - Web Parts en SharePoint 2010Comunidad SharePoint
 
Twig avanzado (sf2Vigo)
Twig avanzado (sf2Vigo)Twig avanzado (sf2Vigo)
Twig avanzado (sf2Vigo)Javier Eguiluz
 
TEMA Nº 5: OBJETOS RELACIONADOS CON LA SALIDA O LA ENTRADA DE LA PÁGINA.
TEMA Nº 5: OBJETOS RELACIONADOS CON LA SALIDA O LA ENTRADA DE LA PÁGINA.TEMA Nº 5: OBJETOS RELACIONADOS CON LA SALIDA O LA ENTRADA DE LA PÁGINA.
TEMA Nº 5: OBJETOS RELACIONADOS CON LA SALIDA O LA ENTRADA DE LA PÁGINA.Anyeni Garay
 
SolidQ Summit 2018 - Todo lo que un integrador de datos debería tener... y pa...
SolidQ Summit 2018 - Todo lo que un integrador de datos debería tener... y pa...SolidQ Summit 2018 - Todo lo que un integrador de datos debería tener... y pa...
SolidQ Summit 2018 - Todo lo que un integrador de datos debería tener... y pa...SolidQ
 

Semelhante a Servlets que manejan datos de formularios HTML (20)

Conferencia 3: solrconfig.xml
Conferencia 3: solrconfig.xmlConferencia 3: solrconfig.xml
Conferencia 3: solrconfig.xml
 
Clase n3 manejo de formularios
Clase n3 manejo de formulariosClase n3 manejo de formularios
Clase n3 manejo de formularios
 
Tema 6 - Formularios en html
Tema 6 - Formularios en htmlTema 6 - Formularios en html
Tema 6 - Formularios en html
 
Php excel
Php excelPhp excel
Php excel
 
06 validación
06 validación06 validación
06 validación
 
Presentacion ajax
Presentacion   ajaxPresentacion   ajax
Presentacion ajax
 
Ajax
AjaxAjax
Ajax
 
Programación web con JSP
Programación web con JSPProgramación web con JSP
Programación web con JSP
 
Practica utilizacion de beans en jsp
Practica  utilizacion de beans en jspPractica  utilizacion de beans en jsp
Practica utilizacion de beans en jsp
 
Jquery para principianes
Jquery para principianesJquery para principianes
Jquery para principianes
 
J M E R L I N P H P
J M E R L I N P H PJ M E R L I N P H P
J M E R L I N P H P
 
Peticiones y respuestas
Peticiones y respuestasPeticiones y respuestas
Peticiones y respuestas
 
Guia N5 Proyectos Web Consultas Php Y My Sql
Guia N5   Proyectos Web   Consultas Php Y My SqlGuia N5   Proyectos Web   Consultas Php Y My Sql
Guia N5 Proyectos Web Consultas Php Y My Sql
 
Bases de Datos en Java - Intro a JDBC
Bases de Datos en Java - Intro a JDBCBases de Datos en Java - Intro a JDBC
Bases de Datos en Java - Intro a JDBC
 
Objetos implicitos jsp
Objetos implicitos jspObjetos implicitos jsp
Objetos implicitos jsp
 
Screen scraping
Screen scrapingScreen scraping
Screen scraping
 
CSA - Web Parts en SharePoint 2010
CSA - Web Parts en SharePoint 2010CSA - Web Parts en SharePoint 2010
CSA - Web Parts en SharePoint 2010
 
Twig avanzado (sf2Vigo)
Twig avanzado (sf2Vigo)Twig avanzado (sf2Vigo)
Twig avanzado (sf2Vigo)
 
TEMA Nº 5: OBJETOS RELACIONADOS CON LA SALIDA O LA ENTRADA DE LA PÁGINA.
TEMA Nº 5: OBJETOS RELACIONADOS CON LA SALIDA O LA ENTRADA DE LA PÁGINA.TEMA Nº 5: OBJETOS RELACIONADOS CON LA SALIDA O LA ENTRADA DE LA PÁGINA.
TEMA Nº 5: OBJETOS RELACIONADOS CON LA SALIDA O LA ENTRADA DE LA PÁGINA.
 
SolidQ Summit 2018 - Todo lo que un integrador de datos debería tener... y pa...
SolidQ Summit 2018 - Todo lo que un integrador de datos debería tener... y pa...SolidQ Summit 2018 - Todo lo que un integrador de datos debería tener... y pa...
SolidQ Summit 2018 - Todo lo que un integrador de datos debería tener... y pa...
 

Mais de jubacalo

MIT App Inventor2 Pintar en Imagen
MIT App Inventor2 Pintar en ImagenMIT App Inventor2 Pintar en Imagen
MIT App Inventor2 Pintar en Imagenjubacalo
 
Cronómetro con MIT App Inventor 2
Cronómetro con MIT App Inventor 2Cronómetro con MIT App Inventor 2
Cronómetro con MIT App Inventor 2jubacalo
 
App Android MiniBanco
App Android MiniBancoApp Android MiniBanco
App Android MiniBancojubacalo
 
Configurar entorno Android
Configurar entorno AndroidConfigurar entorno Android
Configurar entorno Androidjubacalo
 
Crear Base de Datos en Oracle
Crear Base de Datos en OracleCrear Base de Datos en Oracle
Crear Base de Datos en Oraclejubacalo
 
Web de noticias en Ajax
Web de noticias en AjaxWeb de noticias en Ajax
Web de noticias en Ajaxjubacalo
 
Escenarios
EscenariosEscenarios
Escenariosjubacalo
 
Matrices02
Matrices02Matrices02
Matrices02jubacalo
 
Tabla Dinámica
Tabla DinámicaTabla Dinámica
Tabla Dinámicajubacalo
 
Tabla de Datos
Tabla de DatosTabla de Datos
Tabla de Datosjubacalo
 
Textura de agua
Textura de aguaTextura de agua
Textura de aguajubacalo
 
Funciones lógicas y condicionales
Funciones lógicas y condicionalesFunciones lógicas y condicionales
Funciones lógicas y condicionalesjubacalo
 
Java Thread Cronometro
Java Thread CronometroJava Thread Cronometro
Java Thread Cronometrojubacalo
 

Mais de jubacalo (16)

MIT App Inventor2 Pintar en Imagen
MIT App Inventor2 Pintar en ImagenMIT App Inventor2 Pintar en Imagen
MIT App Inventor2 Pintar en Imagen
 
Cronómetro con MIT App Inventor 2
Cronómetro con MIT App Inventor 2Cronómetro con MIT App Inventor 2
Cronómetro con MIT App Inventor 2
 
App Android MiniBanco
App Android MiniBancoApp Android MiniBanco
App Android MiniBanco
 
Configurar entorno Android
Configurar entorno AndroidConfigurar entorno Android
Configurar entorno Android
 
Crear Base de Datos en Oracle
Crear Base de Datos en OracleCrear Base de Datos en Oracle
Crear Base de Datos en Oracle
 
Web de noticias en Ajax
Web de noticias en AjaxWeb de noticias en Ajax
Web de noticias en Ajax
 
Escenarios
EscenariosEscenarios
Escenarios
 
Matrices02
Matrices02Matrices02
Matrices02
 
Gráficos
GráficosGráficos
Gráficos
 
Tabla Dinámica
Tabla DinámicaTabla Dinámica
Tabla Dinámica
 
Tabla de Datos
Tabla de DatosTabla de Datos
Tabla de Datos
 
Textura de agua
Textura de aguaTextura de agua
Textura de agua
 
Funciones lógicas y condicionales
Funciones lógicas y condicionalesFunciones lógicas y condicionales
Funciones lógicas y condicionales
 
Solver
SolverSolver
Solver
 
Word VBA
Word VBAWord VBA
Word VBA
 
Java Thread Cronometro
Java Thread CronometroJava Thread Cronometro
Java Thread Cronometro
 

Último

Posición astronómica y geográfica de Europa.pptx
Posición astronómica y geográfica de Europa.pptxPosición astronómica y geográfica de Europa.pptx
Posición astronómica y geográfica de Europa.pptxBeatrizQuijano2
 
Prueba libre de Geografía para obtención título Bachillerato - 2024
Prueba libre de Geografía para obtención título Bachillerato - 2024Prueba libre de Geografía para obtención título Bachillerato - 2024
Prueba libre de Geografía para obtención título Bachillerato - 2024Juan Martín Martín
 
🦄💫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
 
Prueba de evaluación Geografía e Historia Comunidad de Madrid 4ºESO
Prueba de evaluación Geografía e Historia Comunidad de Madrid 4ºESOPrueba de evaluación Geografía e Historia Comunidad de Madrid 4ºESO
Prueba de evaluación Geografía e Historia Comunidad de Madrid 4ºESOluismii249
 
Plan-de-la-Patria-2019-2025- TERCER PLAN SOCIALISTA DE LA NACIÓN.pdf
Plan-de-la-Patria-2019-2025- TERCER PLAN SOCIALISTA DE LA NACIÓN.pdfPlan-de-la-Patria-2019-2025- TERCER PLAN SOCIALISTA DE LA NACIÓN.pdf
Plan-de-la-Patria-2019-2025- TERCER PLAN SOCIALISTA DE LA NACIÓN.pdfcarolinamartinezsev
 
origen y desarrollo del ensayo literario
origen y desarrollo del ensayo literarioorigen y desarrollo del ensayo literario
origen y desarrollo del ensayo literarioELIASAURELIOCHAVEZCA1
 
CONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptx
CONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptxCONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptx
CONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptxroberthirigoinvasque
 
Feliz Día de la Madre - 5 de Mayo, 2024.pdf
Feliz Día de la Madre - 5 de Mayo, 2024.pdfFeliz Día de la Madre - 5 de Mayo, 2024.pdf
Feliz Día de la Madre - 5 de Mayo, 2024.pdfMercedes Gonzalez
 
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
 
FUERZA Y MOVIMIENTO ciencias cuarto basico.ppt
FUERZA Y MOVIMIENTO ciencias cuarto basico.pptFUERZA Y MOVIMIENTO ciencias cuarto basico.ppt
FUERZA Y MOVIMIENTO ciencias cuarto basico.pptNancyMoreiraMora1
 
Procedimientos para la planificación en los Centros Educativos tipo V ( multi...
Procedimientos para la planificación en los Centros Educativos tipo V ( multi...Procedimientos para la planificación en los Centros Educativos tipo V ( multi...
Procedimientos para la planificación en los Centros Educativos tipo V ( multi...Katherine Concepcion Gonzalez
 
LA LITERATURA DEL BARROCO 2023-2024pptx.pptx
LA LITERATURA DEL BARROCO 2023-2024pptx.pptxLA LITERATURA DEL BARROCO 2023-2024pptx.pptx
LA LITERATURA DEL BARROCO 2023-2024pptx.pptxlclcarmen
 
ACRÓNIMO DE PARÍS PARA SU OLIMPIADA 2024. Por JAVIER SOLIS NOYOLA
ACRÓNIMO DE PARÍS PARA SU OLIMPIADA 2024. Por JAVIER SOLIS NOYOLAACRÓNIMO DE PARÍS PARA SU OLIMPIADA 2024. Por JAVIER SOLIS NOYOLA
ACRÓNIMO DE PARÍS PARA SU OLIMPIADA 2024. Por JAVIER SOLIS NOYOLAJAVIER SOLIS NOYOLA
 
SISTEMA RESPIRATORIO PARA NIÑOS PRIMARIA
SISTEMA RESPIRATORIO PARA NIÑOS PRIMARIASISTEMA RESPIRATORIO PARA NIÑOS PRIMARIA
SISTEMA RESPIRATORIO PARA NIÑOS PRIMARIAFabiolaGarcia751855
 
Prueba de evaluación Geografía e Historia Comunidad de Madrid 2º de la ESO
Prueba de evaluación Geografía e Historia Comunidad de Madrid 2º de la ESOPrueba de evaluación Geografía e Historia Comunidad de Madrid 2º de la ESO
Prueba de evaluación Geografía e Historia Comunidad de Madrid 2º de la ESOluismii249
 

Último (20)

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
 
Posición astronómica y geográfica de Europa.pptx
Posición astronómica y geográfica de Europa.pptxPosición astronómica y geográfica de Europa.pptx
Posición astronómica y geográfica de Europa.pptx
 
Prueba libre de Geografía para obtención título Bachillerato - 2024
Prueba libre de Geografía para obtención título Bachillerato - 2024Prueba libre de Geografía para obtención título Bachillerato - 2024
Prueba libre de Geografía para obtención título Bachillerato - 2024
 
🦄💫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
 
Prueba de evaluación Geografía e Historia Comunidad de Madrid 4ºESO
Prueba de evaluación Geografía e Historia Comunidad de Madrid 4ºESOPrueba de evaluación Geografía e Historia Comunidad de Madrid 4ºESO
Prueba de evaluación Geografía e Historia Comunidad de Madrid 4ºESO
 
Plan-de-la-Patria-2019-2025- TERCER PLAN SOCIALISTA DE LA NACIÓN.pdf
Plan-de-la-Patria-2019-2025- TERCER PLAN SOCIALISTA DE LA NACIÓN.pdfPlan-de-la-Patria-2019-2025- TERCER PLAN SOCIALISTA DE LA NACIÓN.pdf
Plan-de-la-Patria-2019-2025- TERCER PLAN SOCIALISTA DE LA NACIÓN.pdf
 
origen y desarrollo del ensayo literario
origen y desarrollo del ensayo literarioorigen y desarrollo del ensayo literario
origen y desarrollo del ensayo literario
 
CONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptx
CONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptxCONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptx
CONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptx
 
Feliz Día de la Madre - 5 de Mayo, 2024.pdf
Feliz Día de la Madre - 5 de Mayo, 2024.pdfFeliz Día de la Madre - 5 de Mayo, 2024.pdf
Feliz Día de la Madre - 5 de Mayo, 2024.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
 
Supuestos_prácticos_funciones.docx
Supuestos_prácticos_funciones.docxSupuestos_prácticos_funciones.docx
Supuestos_prácticos_funciones.docx
 
FUERZA Y MOVIMIENTO ciencias cuarto basico.ppt
FUERZA Y MOVIMIENTO ciencias cuarto basico.pptFUERZA Y MOVIMIENTO ciencias cuarto basico.ppt
FUERZA Y MOVIMIENTO ciencias cuarto basico.ppt
 
Procedimientos para la planificación en los Centros Educativos tipo V ( multi...
Procedimientos para la planificación en los Centros Educativos tipo V ( multi...Procedimientos para la planificación en los Centros Educativos tipo V ( multi...
Procedimientos para la planificación en los Centros Educativos tipo V ( multi...
 
LA LITERATURA DEL BARROCO 2023-2024pptx.pptx
LA LITERATURA DEL BARROCO 2023-2024pptx.pptxLA LITERATURA DEL BARROCO 2023-2024pptx.pptx
LA LITERATURA DEL BARROCO 2023-2024pptx.pptx
 
Tema 11. Dinámica de la hidrosfera 2024
Tema 11.  Dinámica de la hidrosfera 2024Tema 11.  Dinámica de la hidrosfera 2024
Tema 11. Dinámica de la hidrosfera 2024
 
ACRÓNIMO DE PARÍS PARA SU OLIMPIADA 2024. Por JAVIER SOLIS NOYOLA
ACRÓNIMO DE PARÍS PARA SU OLIMPIADA 2024. Por JAVIER SOLIS NOYOLAACRÓNIMO DE PARÍS PARA SU OLIMPIADA 2024. Por JAVIER SOLIS NOYOLA
ACRÓNIMO DE PARÍS PARA SU OLIMPIADA 2024. Por JAVIER SOLIS NOYOLA
 
SISTEMA RESPIRATORIO PARA NIÑOS PRIMARIA
SISTEMA RESPIRATORIO PARA NIÑOS PRIMARIASISTEMA RESPIRATORIO PARA NIÑOS PRIMARIA
SISTEMA RESPIRATORIO PARA NIÑOS PRIMARIA
 
Power Point E. S.: Los dos testigos.pptx
Power Point E. S.: Los dos testigos.pptxPower Point E. S.: Los dos testigos.pptx
Power Point E. S.: Los dos testigos.pptx
 
Prueba de evaluación Geografía e Historia Comunidad de Madrid 2º de la ESO
Prueba de evaluación Geografía e Historia Comunidad de Madrid 2º de la ESOPrueba de evaluación Geografía e Historia Comunidad de Madrid 2º de la ESO
Prueba de evaluación Geografía e Historia Comunidad de Madrid 2º de la ESO
 
Interpretación de cortes geológicos 2024
Interpretación de cortes geológicos 2024Interpretación de cortes geológicos 2024
Interpretación de cortes geológicos 2024
 

Servlets que manejan datos de formularios HTML

  • 1. Servlets que manejan datos de formularios HTML Formulario HTML que solicita el ingreso del nombre y clave de un usuario. Posteriormente se recuperan los dos parámetros en un servlet y se muestran en otra página generada por el servlet. formulario.html <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>Formulario HTML</title> </head> <body> <form method="post" action="ServletRecolector"> <p>Nombre de usuario: <input type="text" name="usuario" size="20" /></p> <p>Clave: <input type="password" name="clave" size="20" /></p> <p><input type="submit" value="confirmar" /></p> </form> </body> </html>
  • 2. Codificamos la página html con el formulario web que solicita el ingreso del nombre de usuario y su clave… En la propiedad action de la etiqueta form indicamos el nombre del servlet que recuperará los datos del formulario… <form method="post" action="ServletRecolector"> ServletRecolector.java package pkgServForm; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ServletRecolector */ @WebServlet("/ServletRecolector") public class ServletRecolector extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ServletRecolector() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head></head>"); out.println("<body>"); out.println("Usuario:"); out.println(request.getParameter("usuario")); out.println("<br/>Clave:"); out.println(request.getParameter("clave")); out.println("</body>"); out.println("</html>"); } }
  • 3. En la clase ServletRecolector implementamos todo el código en el método doPost, ya que este se ejecuta cuando se envían los datos de un formulario HTML mediante post: <form method="post" action="ServletRecolector"> Para recuperar los datos de los controles text y password del formulario HTML el objeto request de la clase HttpServletRequest dispone de un método llamado getParamenter indicándole el nombre del control a recuperar: request.getParameter("usuario"); request.getParameter("clave"); Del objeto response de la clase HttpServletResponse obtenemos un objeto PrintWriter (mediante su método getWriter) usado para enviar la salida de vuelta al cliente (navegador). PrintWriter out = response.getWriter(); out.println(request.getParameter("clave")); Resultado de la ejecución…
  • 4. Ejemplo02: Servlet que maneja parámetros enviados por POST desde un form que contiene controles de tipo select (cuadro combinado), text (caja de texto), checkbox (se pueden marcar varias opciones), radio (excluyente, sólo se puede seleccionar una opción). El resultado de la ejecución sería… El servlet recupera los parámetros enviados desde el form y los muestra en otra página html que envía al cliente. Estructura de directorios y archivos en el proyecto web dinámico en Eclipse.
  • 5. formulario02.html <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>Insert title here</title> </head> <body> <form method="post" action="ServletRecolector"> <p>Title: <select size="1" name="title"> <option selected="selected">Mr</option> <option>Mrs</option> <option>Miss</option> <option>Ms</option> <option>Other</option> </select></p> <p>Name: <input type="text" name="name" size="20" value="---"/></p> <p>City: <input type="text" name="city" size="20" value="---"/></p> <p>Country: <input type="text" name="country" size="20" value="---"/></p> <p>Telephone: <input type="text" name="tel" size="20" value="---"/></p> <p>Please inform us of your interests:</p> <input type="checkbox" name="interests" value="Sport"/>Sport<br/> <input type="checkbox" name="interests" value="Music"/>Music<br/> <input type="checkbox" name="interests" value="Reading"/>Reading<br/> <input type="checkbox" name="interests" value="TV and Film"/>TV and Film <p>Your age: <input type="radio" name="age" value="25orless" checked="checked"/>Less than 25 <input type="radio" name="age" value="26to40"/>26-40 <input type="radio" name="age" value="41to65"/>41-65 <input type="radio" name="age" value="over65"/>Over 65</p> <p><input type="submit" value="Submit"/></p> </form> </body> </html>
  • 6. ServletRecolector.java package pkgServletForm; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ServletRecolector */ @WebServlet("/ServletRecolector") public class ServletRecolector extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub ServletOutputStream out = response.getOutputStream(); response.setContentType("text/html"); out.println("<html><head><title>Basic Form Processor Output</title></head>"); out.println("<body>"); out.println("<h1>Here is your Form Data</h1>"); //Opción elegida en el cuadro combinado (tratamiento) out.println("Your title is " + request.getParameter("title")); //Parámetros nombre, ciudad, pais y teléfono (individuales text) out.println("<br>Your name is " + request.getParameter("name")); out.println("<br>Your city is " + request.getParameter("city")); out.println("<br>Your country is " + request.getParameter("country")); out.println("<br>Your tel is " + request.getParameter("tel")); // extracting data from the checkbox field (checkbox intereses) String[] interests = request.getParameterValues("interests"); if(interests!=null){ out.println("</br>Your interests include<ul> "); for (int i=0;i<interests.length; i++) { out.println("<li>" + interests[i]); } out.println("</ul>"); }else{ out.println("<p>No tiene aficiones...</p>"); } //Opción elegida (edad radio) out.println("<br>Your age is " + request.getParameter("age")); out.println("</body></html>"); } }
  • 7. getParameterValues public java.lang.String[] getParameterValues(java.lang.String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. If the parameter has a single value, the array has a length of 1. Parameters: name - a String containing the name of the parameter whose value is requested Returns: an array of String objects containing the parameter's values getParameter public java.lang.String getParameter(java.lang.String name) Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data. You should only use this method when you are sure the parameter has only one value. If the parameter might have more than one value, use getParameterValues(java.lang.String). If you use this method with a multivalued parameter, the value returned is equal to the first value in the array returned by getParameterValues. If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via getInputStream() or getReader() can interfere with the execution of this method. Parameters: name - a String specifying the name of the parameter Returns: a String representing the single value of the parameter