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

Insercion directa
Insercion directaInsercion directa
Insercion directa
abelpit2
 
Ejercicios de estructura selectiva anidadas
Ejercicios de estructura selectiva anidadasEjercicios de estructura selectiva anidadas
Ejercicios de estructura selectiva anidadas
Alejandro Pacheco
 
Diagramas De Secuencia
Diagramas De SecuenciaDiagramas De Secuencia
Diagramas De Secuencia
Fabian Garcia
 

Mais procurados (20)

Ejercicios resueltos de programacion
Ejercicios resueltos de programacionEjercicios resueltos de programacion
Ejercicios resueltos de programacion
 
Informe Final Del Proyecto Poo
Informe Final Del Proyecto PooInforme Final Del Proyecto Poo
Informe Final Del Proyecto Poo
 
Ejercicios condicional-if
Ejercicios condicional-if  Ejercicios condicional-if
Ejercicios condicional-if
 
Insercion directa
Insercion directaInsercion directa
Insercion directa
 
Manual para usar raptor(1)
Manual para usar raptor(1)Manual para usar raptor(1)
Manual para usar raptor(1)
 
Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018Kotlin Coroutines in Practice @ KotlinConf 2018
Kotlin Coroutines in Practice @ KotlinConf 2018
 
Listas Pilas Colas
Listas Pilas ColasListas Pilas Colas
Listas Pilas Colas
 
Cuestionario
CuestionarioCuestionario
Cuestionario
 
Ejercicios resueltos de c++
Ejercicios resueltos de c++Ejercicios resueltos de c++
Ejercicios resueltos de c++
 
Les Servlets et JSP
Les Servlets et JSPLes Servlets et JSP
Les Servlets et JSP
 
Ejercicios de estructura selectiva anidadas
Ejercicios de estructura selectiva anidadasEjercicios de estructura selectiva anidadas
Ejercicios de estructura selectiva anidadas
 
Diagramas De Secuencia
Diagramas De SecuenciaDiagramas De Secuencia
Diagramas De Secuencia
 
Controles swing
Controles swingControles swing
Controles swing
 
METODOS DE ORDENAMIENTO
METODOS DE ORDENAMIENTOMETODOS DE ORDENAMIENTO
METODOS DE ORDENAMIENTO
 
Introducción a Django
Introducción a DjangoIntroducción a Django
Introducción a Django
 
Metodo de busqueda secuencial
Metodo de busqueda secuencialMetodo de busqueda secuencial
Metodo de busqueda secuencial
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
 
Conversion de decimal a octal
Conversion de decimal a octalConversion de decimal a octal
Conversion de decimal a octal
 
Cap 02.1 analisis de las estructuras de control(1)
Cap 02.1   analisis de las estructuras de control(1)Cap 02.1   analisis de las estructuras de control(1)
Cap 02.1 analisis de las estructuras de control(1)
 
Búsqueda secuencial y binaria
Búsqueda secuencial y binariaBúsqueda secuencial y binaria
Búsqueda secuencial y binaria
 

Destaque

Java::Acceso a Bases de Datos
Java::Acceso a Bases de DatosJava::Acceso a Bases de Datos
Java::Acceso a Bases de Datos
jubacalo
 
Java Thread Cronometro
Java Thread CronometroJava Thread Cronometro
Java Thread Cronometro
jubacalo
 
Sincronizar Threads
Sincronizar ThreadsSincronizar Threads
Sincronizar Threads
jubacalo
 
Acciones JSP
Acciones JSPAcciones JSP
Acciones JSP
jubacalo
 
Jsp directiva page
Jsp directiva pageJsp directiva page
Jsp directiva page
jubacalo
 
Proyecto JSP
Proyecto JSPProyecto JSP
Proyecto JSP
jubacalo
 
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
 
Java ArrayList Iterator
Java ArrayList IteratorJava ArrayList Iterator
Java ArrayList Iterator
jubacalo
 
Java HashMap
Java HashMapJava HashMap
Java HashMap
jubacalo
 

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 html
Pamela Rodriguez
 
Php excel
Php excelPhp excel
Php excel
pcuseth
 
Practica utilizacion de beans en jsp
Practica  utilizacion de beans en jspPractica  utilizacion de beans en jsp
Practica utilizacion de beans en jsp
Boris Salleg
 
Peticiones y respuestas
Peticiones y respuestasPeticiones y respuestas
Peticiones y respuestas
Edwin Enriquez
 
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
 

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

Proyecto de aprendizaje dia de la madre MINT.pdf
Proyecto de aprendizaje dia de la madre MINT.pdfProyecto de aprendizaje dia de la madre MINT.pdf
Proyecto de aprendizaje dia de la madre MINT.pdf
patriciaines1993
 
RESULTADOS DE LA EVALUACIÓN DIAGNÓSTICA 2024 - ACTUALIZADA.pptx
RESULTADOS DE LA EVALUACIÓN DIAGNÓSTICA 2024 - ACTUALIZADA.pptxRESULTADOS DE LA EVALUACIÓN DIAGNÓSTICA 2024 - ACTUALIZADA.pptx
RESULTADOS DE LA EVALUACIÓN DIAGNÓSTICA 2024 - ACTUALIZADA.pptx
pvtablets2023
 
🦄💫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
EliaHernndez7
 
Concepto y definición de tipos de Datos Abstractos en c++.pptx
Concepto y definición de tipos de Datos Abstractos en c++.pptxConcepto y definición de tipos de Datos Abstractos en c++.pptx
Concepto y definición de tipos de Datos Abstractos en c++.pptx
Fernando Solis
 
6°_GRADO_-_MAYO_06 para sexto grado de primaria
6°_GRADO_-_MAYO_06 para sexto grado de primaria6°_GRADO_-_MAYO_06 para sexto grado de primaria
6°_GRADO_-_MAYO_06 para sexto grado de primaria
Wilian24
 
TALLER DE DEMOCRACIA Y GOBIERNO ESCOLAR-COMPETENCIAS N°3.docx
TALLER DE DEMOCRACIA Y GOBIERNO ESCOLAR-COMPETENCIAS N°3.docxTALLER DE DEMOCRACIA Y GOBIERNO ESCOLAR-COMPETENCIAS N°3.docx
TALLER DE DEMOCRACIA Y GOBIERNO ESCOLAR-COMPETENCIAS N°3.docx
NadiaMartnez11
 
TEMA 14.DERIVACIONES ECONÓMICAS, SOCIALES Y POLÍTICAS DEL PROCESO DE INTEGRAC...
TEMA 14.DERIVACIONES ECONÓMICAS, SOCIALES Y POLÍTICAS DEL PROCESO DE INTEGRAC...TEMA 14.DERIVACIONES ECONÓMICAS, SOCIALES Y POLÍTICAS DEL PROCESO DE INTEGRAC...
TEMA 14.DERIVACIONES ECONÓMICAS, SOCIALES Y POLÍTICAS DEL PROCESO DE INTEGRAC...
jlorentemartos
 

Último (20)

CONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptx
CONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptxCONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptx
CONCURSO NACIONAL JOSE MARIA ARGUEDAS.pptx
 
Proyecto de aprendizaje dia de la madre MINT.pdf
Proyecto de aprendizaje dia de la madre MINT.pdfProyecto de aprendizaje dia de la madre MINT.pdf
Proyecto de aprendizaje dia de la madre MINT.pdf
 
RESULTADOS DE LA EVALUACIÓN DIAGNÓSTICA 2024 - ACTUALIZADA.pptx
RESULTADOS DE LA EVALUACIÓN DIAGNÓSTICA 2024 - ACTUALIZADA.pptxRESULTADOS DE LA EVALUACIÓN DIAGNÓSTICA 2024 - ACTUALIZADA.pptx
RESULTADOS DE LA EVALUACIÓN DIAGNÓSTICA 2024 - ACTUALIZADA.pptx
 
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
 
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
 
🦄💫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
 
Concepto y definición de tipos de Datos Abstractos en c++.pptx
Concepto y definición de tipos de Datos Abstractos en c++.pptxConcepto y definición de tipos de Datos Abstractos en c++.pptx
Concepto y definición de tipos de Datos Abstractos en c++.pptx
 
Tema 19. Inmunología y el sistema inmunitario 2024
Tema 19. Inmunología y el sistema inmunitario 2024Tema 19. Inmunología y el sistema inmunitario 2024
Tema 19. Inmunología y el sistema inmunitario 2024
 
6°_GRADO_-_MAYO_06 para sexto grado de primaria
6°_GRADO_-_MAYO_06 para sexto grado de primaria6°_GRADO_-_MAYO_06 para sexto grado de primaria
6°_GRADO_-_MAYO_06 para sexto grado de primaria
 
TALLER DE DEMOCRACIA Y GOBIERNO ESCOLAR-COMPETENCIAS N°3.docx
TALLER DE DEMOCRACIA Y GOBIERNO ESCOLAR-COMPETENCIAS N°3.docxTALLER DE DEMOCRACIA Y GOBIERNO ESCOLAR-COMPETENCIAS N°3.docx
TALLER DE DEMOCRACIA Y GOBIERNO ESCOLAR-COMPETENCIAS N°3.docx
 
SISTEMA RESPIRATORIO PARA NIÑOS PRIMARIA
SISTEMA RESPIRATORIO PARA NIÑOS PRIMARIASISTEMA RESPIRATORIO PARA NIÑOS PRIMARIA
SISTEMA RESPIRATORIO PARA NIÑOS PRIMARIA
 
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
 
La Sostenibilidad Corporativa. Administración Ambiental
La Sostenibilidad Corporativa. Administración AmbientalLa Sostenibilidad Corporativa. Administración Ambiental
La Sostenibilidad Corporativa. Administración Ambiental
 
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
 
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
 
OCTAVO SEGUNDO PERIODO. EMPRENDIEMIENTO VS
OCTAVO SEGUNDO PERIODO. EMPRENDIEMIENTO VSOCTAVO SEGUNDO PERIODO. EMPRENDIEMIENTO VS
OCTAVO SEGUNDO PERIODO. EMPRENDIEMIENTO VS
 
TEMA 14.DERIVACIONES ECONÓMICAS, SOCIALES Y POLÍTICAS DEL PROCESO DE INTEGRAC...
TEMA 14.DERIVACIONES ECONÓMICAS, SOCIALES Y POLÍTICAS DEL PROCESO DE INTEGRAC...TEMA 14.DERIVACIONES ECONÓMICAS, SOCIALES Y POLÍTICAS DEL PROCESO DE INTEGRAC...
TEMA 14.DERIVACIONES ECONÓMICAS, SOCIALES Y POLÍTICAS DEL PROCESO DE INTEGRAC...
 
Sesión de clase: Fe contra todo pronóstico
Sesión de clase: Fe contra todo pronósticoSesión de clase: Fe contra todo pronóstico
Sesión de clase: Fe contra todo pronóstico
 
TIENDAS MASS MINIMARKET ESTUDIO DE MERCADO
TIENDAS MASS MINIMARKET ESTUDIO DE MERCADOTIENDAS MASS MINIMARKET ESTUDIO DE MERCADO
TIENDAS MASS MINIMARKET ESTUDIO DE MERCADO
 

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