Servlets que manejan datos de formularios HTML

13,043
-1

Published on

Servlets que manejan datos de formularios HTML

Published in: Education
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
13,043
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
253
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Servlets que manejan datos de formularios HTML

  1. 1. Servlets que manejan datos de formularios HTMLFormulario HTML que solicita el ingreso del nombre y clave de un usuario.Posteriormente se recuperan los dos parámetros en un servlet y se muestranen 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. 2. Codificamos la página html con el formulario web que solicita el ingreso delnombre de usuario y su clave…En la propiedad action de la etiqueta form indicamos el nombre del servletque recuperará los datos del formulario…<form method="post" action="ServletRecolector">ServletRecolector.javapackage 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) throwsServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, 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. 3. En la clase ServletRecolector implementamos todo el código en el métododoPost, ya que este se ejecuta cuando se envían los datos de un formularioHTML mediante post:<form method="post" action="ServletRecolector">Para recuperar los datos de los controles text y password del formulario HTMLel objeto request de la clase HttpServletRequest dispone de un método llamadogetParamenter indicándole el nombre del control a recuperar: request.getParameter("usuario"); request.getParameter("clave");Del objeto response de la clase HttpServletResponse obtenemos un objetoPrintWriter (mediante su método getWriter) usado para enviar la salida devuelta al cliente (navegador).PrintWriter out = response.getWriter();out.println(request.getParameter("clave"));Resultado de la ejecución…
  4. 4. Ejemplo02: Servlet que maneja parámetros enviados por POST desde un form quecontiene controles de tipo select (cuadro combinado), text (caja de texto),checkbox (se pueden marcar varias opciones), radio (excluyente, sólo se puedeseleccionar una opción).El resultado de la ejecución sería…El servlet recupera los parámetros enviados desde el form y los muestra enotra página html que envía al cliente.Estructura de directorios y archivos en el proyecto web dinámico en Eclipse.
  5. 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. 6. ServletRecolector.javapackage 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) throwsServletException, 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. 7. getParameterValuespublic 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 parameters valuesgetParameterpublic 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

×