SlideShare une entreprise Scribd logo
1  sur  7
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC PresentationVolkan Uzun
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency InjectionNir Kaufman
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Lessons Learned from Using Next.js in Production
Lessons Learned from Using Next.js in ProductionLessons Learned from Using Next.js in Production
Lessons Learned from Using Next.js in ProductionPanjamapong Sermsawatsri
 

Tendances (20)

JUnit 4
JUnit 4JUnit 4
JUnit 4
 
JDBC
JDBCJDBC
JDBC
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
JavaFX Overview
JavaFX OverviewJavaFX Overview
JavaFX Overview
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Php forms
Php formsPhp forms
Php forms
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Lessons Learned from Using Next.js in Production
Lessons Learned from Using Next.js in ProductionLessons Learned from Using Next.js in Production
Lessons Learned from Using Next.js in Production
 
Nouveautés Java 9-10-11
Nouveautés Java 9-10-11Nouveautés Java 9-10-11
Nouveautés Java 9-10-11
 

En vedette

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
 

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

Similaire à 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
 

Similaire à 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...
 

Plus 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
 

Plus 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
 

Dernier

Fichas de Matemática DE SEGUNDO DE SECUNDARIA.pdf
Fichas de Matemática DE SEGUNDO DE SECUNDARIA.pdfFichas de Matemática DE SEGUNDO DE SECUNDARIA.pdf
Fichas de Matemática DE SEGUNDO DE SECUNDARIA.pdfssuser50d1252
 
Presentación Bloque 3 Actividad 2 transversal.pptx
Presentación Bloque 3 Actividad 2 transversal.pptxPresentación Bloque 3 Actividad 2 transversal.pptx
Presentación Bloque 3 Actividad 2 transversal.pptxRosabel UA
 
PROGRAMACIÓN CURRICULAR - DPCC- 5°-2024.pdf
PROGRAMACIÓN CURRICULAR - DPCC- 5°-2024.pdfPROGRAMACIÓN CURRICULAR - DPCC- 5°-2024.pdf
PROGRAMACIÓN CURRICULAR - DPCC- 5°-2024.pdfMaritza438836
 
Si cuidamos el mundo, tendremos un mundo mejor.
Si cuidamos el mundo, tendremos un mundo mejor.Si cuidamos el mundo, tendremos un mundo mejor.
Si cuidamos el mundo, tendremos un mundo mejor.monthuerta17
 
describimos como son afectados las regiones naturales del peru por la ola de ...
describimos como son afectados las regiones naturales del peru por la ola de ...describimos como son afectados las regiones naturales del peru por la ola de ...
describimos como son afectados las regiones naturales del peru por la ola de ...DavidBautistaFlores1
 
PRIMER GRADO SOY LECTOR PART1- MD EDUCATIVO.pdf
PRIMER GRADO SOY LECTOR PART1- MD  EDUCATIVO.pdfPRIMER GRADO SOY LECTOR PART1- MD  EDUCATIVO.pdf
PRIMER GRADO SOY LECTOR PART1- MD EDUCATIVO.pdfGabrieldeJesusLopezG
 
Contextualización y aproximación al objeto de estudio de investigación cualit...
Contextualización y aproximación al objeto de estudio de investigación cualit...Contextualización y aproximación al objeto de estudio de investigación cualit...
Contextualización y aproximación al objeto de estudio de investigación cualit...Angélica Soledad Vega Ramírez
 
DIDÁCTICA DE LA EDUCACIÓN SUPERIOR- DR LENIN CARI MOGROVEJO
DIDÁCTICA DE LA EDUCACIÓN SUPERIOR- DR LENIN CARI MOGROVEJODIDÁCTICA DE LA EDUCACIÓN SUPERIOR- DR LENIN CARI MOGROVEJO
DIDÁCTICA DE LA EDUCACIÓN SUPERIOR- DR LENIN CARI MOGROVEJOLeninCariMogrovejo
 
Fichas de Matemática TERCERO DE SECUNDARIA.pdf
Fichas de Matemática TERCERO DE SECUNDARIA.pdfFichas de Matemática TERCERO DE SECUNDARIA.pdf
Fichas de Matemática TERCERO DE SECUNDARIA.pdfssuser50d1252
 
4° UNIDAD 2 SALUD,ALIMENTACIÓN Y DÍA DE LA MADRE 933623393 PROF YESSENIA CN.docx
4° UNIDAD 2 SALUD,ALIMENTACIÓN Y DÍA DE LA MADRE 933623393 PROF YESSENIA CN.docx4° UNIDAD 2 SALUD,ALIMENTACIÓN Y DÍA DE LA MADRE 933623393 PROF YESSENIA CN.docx
4° UNIDAD 2 SALUD,ALIMENTACIÓN Y DÍA DE LA MADRE 933623393 PROF YESSENIA CN.docxMagalyDacostaPea
 
Fichas de matemática DE PRIMERO DE SECUNDARIA.pdf
Fichas de matemática DE PRIMERO DE SECUNDARIA.pdfFichas de matemática DE PRIMERO DE SECUNDARIA.pdf
Fichas de matemática DE PRIMERO DE SECUNDARIA.pdfssuser50d1252
 
Actividad transversal 2-bloque 2. Actualización 2024
Actividad transversal 2-bloque 2. Actualización 2024Actividad transversal 2-bloque 2. Actualización 2024
Actividad transversal 2-bloque 2. Actualización 2024Rosabel UA
 
4° SES MATE DESCOMP. ADIT. DE NUMEROS SOBRE CASOS DE DENGUE 9-4-24 (1).docx
4° SES MATE DESCOMP. ADIT. DE NUMEROS SOBRE CASOS DE DENGUE     9-4-24 (1).docx4° SES MATE DESCOMP. ADIT. DE NUMEROS SOBRE CASOS DE DENGUE     9-4-24 (1).docx
4° SES MATE DESCOMP. ADIT. DE NUMEROS SOBRE CASOS DE DENGUE 9-4-24 (1).docxMagalyDacostaPea
 
Secuencia didáctica.DOÑA CLEMENTINA.2024.docx
Secuencia didáctica.DOÑA CLEMENTINA.2024.docxSecuencia didáctica.DOÑA CLEMENTINA.2024.docx
Secuencia didáctica.DOÑA CLEMENTINA.2024.docxNataliaGonzalez619348
 
HISTORIETA: AVENTURAS VERDES (ECOLOGÍA).
HISTORIETA: AVENTURAS VERDES (ECOLOGÍA).HISTORIETA: AVENTURAS VERDES (ECOLOGÍA).
HISTORIETA: AVENTURAS VERDES (ECOLOGÍA).hebegris04
 
IV SES LUN 15 TUTO CUIDO MI MENTE CUIDANDO MI CUERPO YESSENIA 933623393 NUEV...
IV SES LUN 15 TUTO CUIDO MI MENTE CUIDANDO MI CUERPO  YESSENIA 933623393 NUEV...IV SES LUN 15 TUTO CUIDO MI MENTE CUIDANDO MI CUERPO  YESSENIA 933623393 NUEV...
IV SES LUN 15 TUTO CUIDO MI MENTE CUIDANDO MI CUERPO YESSENIA 933623393 NUEV...YobanaZevallosSantil1
 
HISPANIDAD - La cultura común de la HISPANOAMERICA
HISPANIDAD - La cultura común de la HISPANOAMERICAHISPANIDAD - La cultura común de la HISPANOAMERICA
HISPANIDAD - La cultura común de la HISPANOAMERICAJesus Gonzalez Losada
 
libro grafismo fonético guía de uso para el lenguaje
libro grafismo fonético guía de uso para el lenguajelibro grafismo fonético guía de uso para el lenguaje
libro grafismo fonético guía de uso para el lenguajeKattyMoran3
 
ENSEÑAR ACUIDAR EL MEDIO AMBIENTE ES ENSEÑAR A VALORAR LA VIDA.
ENSEÑAR ACUIDAR  EL MEDIO AMBIENTE ES ENSEÑAR A VALORAR LA VIDA.ENSEÑAR ACUIDAR  EL MEDIO AMBIENTE ES ENSEÑAR A VALORAR LA VIDA.
ENSEÑAR ACUIDAR EL MEDIO AMBIENTE ES ENSEÑAR A VALORAR LA VIDA.karlazoegarciagarcia
 

Dernier (20)

Fichas de Matemática DE SEGUNDO DE SECUNDARIA.pdf
Fichas de Matemática DE SEGUNDO DE SECUNDARIA.pdfFichas de Matemática DE SEGUNDO DE SECUNDARIA.pdf
Fichas de Matemática DE SEGUNDO DE SECUNDARIA.pdf
 
Presentación Bloque 3 Actividad 2 transversal.pptx
Presentación Bloque 3 Actividad 2 transversal.pptxPresentación Bloque 3 Actividad 2 transversal.pptx
Presentación Bloque 3 Actividad 2 transversal.pptx
 
PROGRAMACIÓN CURRICULAR - DPCC- 5°-2024.pdf
PROGRAMACIÓN CURRICULAR - DPCC- 5°-2024.pdfPROGRAMACIÓN CURRICULAR - DPCC- 5°-2024.pdf
PROGRAMACIÓN CURRICULAR - DPCC- 5°-2024.pdf
 
Si cuidamos el mundo, tendremos un mundo mejor.
Si cuidamos el mundo, tendremos un mundo mejor.Si cuidamos el mundo, tendremos un mundo mejor.
Si cuidamos el mundo, tendremos un mundo mejor.
 
describimos como son afectados las regiones naturales del peru por la ola de ...
describimos como son afectados las regiones naturales del peru por la ola de ...describimos como son afectados las regiones naturales del peru por la ola de ...
describimos como son afectados las regiones naturales del peru por la ola de ...
 
PRIMER GRADO SOY LECTOR PART1- MD EDUCATIVO.pdf
PRIMER GRADO SOY LECTOR PART1- MD  EDUCATIVO.pdfPRIMER GRADO SOY LECTOR PART1- MD  EDUCATIVO.pdf
PRIMER GRADO SOY LECTOR PART1- MD EDUCATIVO.pdf
 
El Bullying.
El Bullying.El Bullying.
El Bullying.
 
Contextualización y aproximación al objeto de estudio de investigación cualit...
Contextualización y aproximación al objeto de estudio de investigación cualit...Contextualización y aproximación al objeto de estudio de investigación cualit...
Contextualización y aproximación al objeto de estudio de investigación cualit...
 
DIDÁCTICA DE LA EDUCACIÓN SUPERIOR- DR LENIN CARI MOGROVEJO
DIDÁCTICA DE LA EDUCACIÓN SUPERIOR- DR LENIN CARI MOGROVEJODIDÁCTICA DE LA EDUCACIÓN SUPERIOR- DR LENIN CARI MOGROVEJO
DIDÁCTICA DE LA EDUCACIÓN SUPERIOR- DR LENIN CARI MOGROVEJO
 
Fichas de Matemática TERCERO DE SECUNDARIA.pdf
Fichas de Matemática TERCERO DE SECUNDARIA.pdfFichas de Matemática TERCERO DE SECUNDARIA.pdf
Fichas de Matemática TERCERO DE SECUNDARIA.pdf
 
4° UNIDAD 2 SALUD,ALIMENTACIÓN Y DÍA DE LA MADRE 933623393 PROF YESSENIA CN.docx
4° UNIDAD 2 SALUD,ALIMENTACIÓN Y DÍA DE LA MADRE 933623393 PROF YESSENIA CN.docx4° UNIDAD 2 SALUD,ALIMENTACIÓN Y DÍA DE LA MADRE 933623393 PROF YESSENIA CN.docx
4° UNIDAD 2 SALUD,ALIMENTACIÓN Y DÍA DE LA MADRE 933623393 PROF YESSENIA CN.docx
 
Fichas de matemática DE PRIMERO DE SECUNDARIA.pdf
Fichas de matemática DE PRIMERO DE SECUNDARIA.pdfFichas de matemática DE PRIMERO DE SECUNDARIA.pdf
Fichas de matemática DE PRIMERO DE SECUNDARIA.pdf
 
Actividad transversal 2-bloque 2. Actualización 2024
Actividad transversal 2-bloque 2. Actualización 2024Actividad transversal 2-bloque 2. Actualización 2024
Actividad transversal 2-bloque 2. Actualización 2024
 
4° SES MATE DESCOMP. ADIT. DE NUMEROS SOBRE CASOS DE DENGUE 9-4-24 (1).docx
4° SES MATE DESCOMP. ADIT. DE NUMEROS SOBRE CASOS DE DENGUE     9-4-24 (1).docx4° SES MATE DESCOMP. ADIT. DE NUMEROS SOBRE CASOS DE DENGUE     9-4-24 (1).docx
4° SES MATE DESCOMP. ADIT. DE NUMEROS SOBRE CASOS DE DENGUE 9-4-24 (1).docx
 
Secuencia didáctica.DOÑA CLEMENTINA.2024.docx
Secuencia didáctica.DOÑA CLEMENTINA.2024.docxSecuencia didáctica.DOÑA CLEMENTINA.2024.docx
Secuencia didáctica.DOÑA CLEMENTINA.2024.docx
 
HISTORIETA: AVENTURAS VERDES (ECOLOGÍA).
HISTORIETA: AVENTURAS VERDES (ECOLOGÍA).HISTORIETA: AVENTURAS VERDES (ECOLOGÍA).
HISTORIETA: AVENTURAS VERDES (ECOLOGÍA).
 
IV SES LUN 15 TUTO CUIDO MI MENTE CUIDANDO MI CUERPO YESSENIA 933623393 NUEV...
IV SES LUN 15 TUTO CUIDO MI MENTE CUIDANDO MI CUERPO  YESSENIA 933623393 NUEV...IV SES LUN 15 TUTO CUIDO MI MENTE CUIDANDO MI CUERPO  YESSENIA 933623393 NUEV...
IV SES LUN 15 TUTO CUIDO MI MENTE CUIDANDO MI CUERPO YESSENIA 933623393 NUEV...
 
HISPANIDAD - La cultura común de la HISPANOAMERICA
HISPANIDAD - La cultura común de la HISPANOAMERICAHISPANIDAD - La cultura común de la HISPANOAMERICA
HISPANIDAD - La cultura común de la HISPANOAMERICA
 
libro grafismo fonético guía de uso para el lenguaje
libro grafismo fonético guía de uso para el lenguajelibro grafismo fonético guía de uso para el lenguaje
libro grafismo fonético guía de uso para el lenguaje
 
ENSEÑAR ACUIDAR EL MEDIO AMBIENTE ES ENSEÑAR A VALORAR LA VIDA.
ENSEÑAR ACUIDAR  EL MEDIO AMBIENTE ES ENSEÑAR A VALORAR LA VIDA.ENSEÑAR ACUIDAR  EL MEDIO AMBIENTE ES ENSEÑAR A VALORAR LA VIDA.
ENSEÑAR ACUIDAR EL MEDIO AMBIENTE ES ENSEÑAR A VALORAR LA VIDA.
 

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