SlideShare una empresa de Scribd logo
1 de 7
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
REST API
REST APIREST API
REST API
 
Json
JsonJson
Json
 
RESTful API - Best Practices
RESTful API - Best PracticesRESTful API - Best Practices
RESTful API - Best Practices
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORM
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 

Destacado

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
 

Destacado (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
 

Similar 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
 

Similar 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...
 

Más 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
 

Más 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

SINTAXIS DE LA ORACIÓN SIMPLE 2023-2024.pptx
SINTAXIS DE LA ORACIÓN SIMPLE 2023-2024.pptxSINTAXIS DE LA ORACIÓN SIMPLE 2023-2024.pptx
SINTAXIS DE LA ORACIÓN SIMPLE 2023-2024.pptxlclcarmen
 
Los Nueve Principios del Desempeño de la Sostenibilidad
Los Nueve Principios del Desempeño de la SostenibilidadLos Nueve Principios del Desempeño de la Sostenibilidad
Los Nueve Principios del Desempeño de la SostenibilidadJonathanCovena1
 
LINEAMIENTOS INICIO DEL AÑO LECTIVO 2024-2025.pptx
LINEAMIENTOS INICIO DEL AÑO LECTIVO 2024-2025.pptxLINEAMIENTOS INICIO DEL AÑO LECTIVO 2024-2025.pptx
LINEAMIENTOS INICIO DEL AÑO LECTIVO 2024-2025.pptxdanalikcruz2000
 
TRIPTICO-SISTEMA-MUSCULAR. PARA NIÑOS DE PRIMARIA
TRIPTICO-SISTEMA-MUSCULAR. PARA NIÑOS DE PRIMARIATRIPTICO-SISTEMA-MUSCULAR. PARA NIÑOS DE PRIMARIA
TRIPTICO-SISTEMA-MUSCULAR. PARA NIÑOS DE PRIMARIAAbelardoVelaAlbrecht1
 
Instrucciones para la aplicacion de la PAA-2024b - (Mayo 2024)
Instrucciones para la aplicacion de la PAA-2024b - (Mayo 2024)Instrucciones para la aplicacion de la PAA-2024b - (Mayo 2024)
Instrucciones para la aplicacion de la PAA-2024b - (Mayo 2024)veganet
 
Día de la Madre Tierra-1.pdf día mundial
Día de la Madre Tierra-1.pdf día mundialDía de la Madre Tierra-1.pdf día mundial
Día de la Madre Tierra-1.pdf día mundialpatriciaines1993
 
Introducción:Los objetivos de Desarrollo Sostenible
Introducción:Los objetivos de Desarrollo SostenibleIntroducción:Los objetivos de Desarrollo Sostenible
Introducción:Los objetivos de Desarrollo SostenibleJonathanCovena1
 
Uses of simple past and time expressions
Uses of simple past and time expressionsUses of simple past and time expressions
Uses of simple past and time expressionsConsueloSantana3
 
DECÁGOLO DEL GENERAL ELOY ALFARO DELGADO
DECÁGOLO DEL GENERAL ELOY ALFARO DELGADODECÁGOLO DEL GENERAL ELOY ALFARO DELGADO
DECÁGOLO DEL GENERAL ELOY ALFARO DELGADOJosé Luis Palma
 
La evolucion de la especie humana-primero de secundaria
La evolucion de la especie humana-primero de secundariaLa evolucion de la especie humana-primero de secundaria
La evolucion de la especie humana-primero de secundariamarco carlos cuyo
 
PINTURA ITALIANA DEL CINQUECENTO (SIGLO XVI).ppt
PINTURA ITALIANA DEL CINQUECENTO (SIGLO XVI).pptPINTURA ITALIANA DEL CINQUECENTO (SIGLO XVI).ppt
PINTURA ITALIANA DEL CINQUECENTO (SIGLO XVI).pptAlberto Rubio
 
periodico mural y sus partes y caracteristicas
periodico mural y sus partes y caracteristicasperiodico mural y sus partes y caracteristicas
periodico mural y sus partes y caracteristicas123yudy
 
CIENCIAS NATURALES 4 TO ambientes .docx
CIENCIAS NATURALES 4 TO  ambientes .docxCIENCIAS NATURALES 4 TO  ambientes .docx
CIENCIAS NATURALES 4 TO ambientes .docxAgustinaNuez21
 
BIOLOGIA_banco de preguntas_editorial icfes examen de estado .pdf
BIOLOGIA_banco de preguntas_editorial icfes examen de estado .pdfBIOLOGIA_banco de preguntas_editorial icfes examen de estado .pdf
BIOLOGIA_banco de preguntas_editorial icfes examen de estado .pdfCESARMALAGA4
 
Mapa Mental de estrategias de articulación de las areas curriculares.pdf
Mapa Mental de estrategias de articulación de las areas curriculares.pdfMapa Mental de estrategias de articulación de las areas curriculares.pdf
Mapa Mental de estrategias de articulación de las areas curriculares.pdfvictorbeltuce
 
SISTEMA INMUNE FISIOLOGIA MEDICA UNSL 2024
SISTEMA INMUNE FISIOLOGIA MEDICA UNSL 2024SISTEMA INMUNE FISIOLOGIA MEDICA UNSL 2024
SISTEMA INMUNE FISIOLOGIA MEDICA UNSL 2024gharce
 

Último (20)

SINTAXIS DE LA ORACIÓN SIMPLE 2023-2024.pptx
SINTAXIS DE LA ORACIÓN SIMPLE 2023-2024.pptxSINTAXIS DE LA ORACIÓN SIMPLE 2023-2024.pptx
SINTAXIS DE LA ORACIÓN SIMPLE 2023-2024.pptx
 
Los Nueve Principios del Desempeño de la Sostenibilidad
Los Nueve Principios del Desempeño de la SostenibilidadLos Nueve Principios del Desempeño de la Sostenibilidad
Los Nueve Principios del Desempeño de la Sostenibilidad
 
LINEAMIENTOS INICIO DEL AÑO LECTIVO 2024-2025.pptx
LINEAMIENTOS INICIO DEL AÑO LECTIVO 2024-2025.pptxLINEAMIENTOS INICIO DEL AÑO LECTIVO 2024-2025.pptx
LINEAMIENTOS INICIO DEL AÑO LECTIVO 2024-2025.pptx
 
TRIPTICO-SISTEMA-MUSCULAR. PARA NIÑOS DE PRIMARIA
TRIPTICO-SISTEMA-MUSCULAR. PARA NIÑOS DE PRIMARIATRIPTICO-SISTEMA-MUSCULAR. PARA NIÑOS DE PRIMARIA
TRIPTICO-SISTEMA-MUSCULAR. PARA NIÑOS DE PRIMARIA
 
Instrucciones para la aplicacion de la PAA-2024b - (Mayo 2024)
Instrucciones para la aplicacion de la PAA-2024b - (Mayo 2024)Instrucciones para la aplicacion de la PAA-2024b - (Mayo 2024)
Instrucciones para la aplicacion de la PAA-2024b - (Mayo 2024)
 
Día de la Madre Tierra-1.pdf día mundial
Día de la Madre Tierra-1.pdf día mundialDía de la Madre Tierra-1.pdf día mundial
Día de la Madre Tierra-1.pdf día mundial
 
Introducción:Los objetivos de Desarrollo Sostenible
Introducción:Los objetivos de Desarrollo SostenibleIntroducción:Los objetivos de Desarrollo Sostenible
Introducción:Los objetivos de Desarrollo Sostenible
 
Uses of simple past and time expressions
Uses of simple past and time expressionsUses of simple past and time expressions
Uses of simple past and time expressions
 
DECÁGOLO DEL GENERAL ELOY ALFARO DELGADO
DECÁGOLO DEL GENERAL ELOY ALFARO DELGADODECÁGOLO DEL GENERAL ELOY ALFARO DELGADO
DECÁGOLO DEL GENERAL ELOY ALFARO DELGADO
 
TL/CNL – 2.ª FASE .
TL/CNL – 2.ª FASE                       .TL/CNL – 2.ª FASE                       .
TL/CNL – 2.ª FASE .
 
La evolucion de la especie humana-primero de secundaria
La evolucion de la especie humana-primero de secundariaLa evolucion de la especie humana-primero de secundaria
La evolucion de la especie humana-primero de secundaria
 
PINTURA ITALIANA DEL CINQUECENTO (SIGLO XVI).ppt
PINTURA ITALIANA DEL CINQUECENTO (SIGLO XVI).pptPINTURA ITALIANA DEL CINQUECENTO (SIGLO XVI).ppt
PINTURA ITALIANA DEL CINQUECENTO (SIGLO XVI).ppt
 
periodico mural y sus partes y caracteristicas
periodico mural y sus partes y caracteristicasperiodico mural y sus partes y caracteristicas
periodico mural y sus partes y caracteristicas
 
PPTX: La luz brilla en la oscuridad.pptx
PPTX: La luz brilla en la oscuridad.pptxPPTX: La luz brilla en la oscuridad.pptx
PPTX: La luz brilla en la oscuridad.pptx
 
CIENCIAS NATURALES 4 TO ambientes .docx
CIENCIAS NATURALES 4 TO  ambientes .docxCIENCIAS NATURALES 4 TO  ambientes .docx
CIENCIAS NATURALES 4 TO ambientes .docx
 
BIOLOGIA_banco de preguntas_editorial icfes examen de estado .pdf
BIOLOGIA_banco de preguntas_editorial icfes examen de estado .pdfBIOLOGIA_banco de preguntas_editorial icfes examen de estado .pdf
BIOLOGIA_banco de preguntas_editorial icfes examen de estado .pdf
 
Mapa Mental de estrategias de articulación de las areas curriculares.pdf
Mapa Mental de estrategias de articulación de las areas curriculares.pdfMapa Mental de estrategias de articulación de las areas curriculares.pdf
Mapa Mental de estrategias de articulación de las areas curriculares.pdf
 
DIA INTERNACIONAL DAS FLORESTAS .
DIA INTERNACIONAL DAS FLORESTAS         .DIA INTERNACIONAL DAS FLORESTAS         .
DIA INTERNACIONAL DAS FLORESTAS .
 
SISTEMA INMUNE FISIOLOGIA MEDICA UNSL 2024
SISTEMA INMUNE FISIOLOGIA MEDICA UNSL 2024SISTEMA INMUNE FISIOLOGIA MEDICA UNSL 2024
SISTEMA INMUNE FISIOLOGIA MEDICA UNSL 2024
 
VISITA À PROTEÇÃO CIVIL _
VISITA À PROTEÇÃO CIVIL                  _VISITA À PROTEÇÃO CIVIL                  _
VISITA À PROTEÇÃO CIVIL _
 

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