A continuación voy a mostrar una pequeña aplicación de ejemplo
para utilizar AJAX en nuestra aplicación de Java. Para este ejemplo utilizare
el IDE de Eclipse.
Descargar código: aqui
Ejemplo funcionando:
Descargar código: aqui
Ejemplo funcionando:
Paso 1: Crear el proyecto
El proyecto lo llamaremos "EjemploAJAX".
Marcaremos esta opción para que nos genere nuestro archivo “web.xml” que necesitaremos más
adelante.
Paso 2: Creamos nuestro
fichero "JSP" inicial que nombraremos “index.jsp”.
Nuestro fichero "index.jsp" contendrá el siguiente código.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> </script> <script> $(document).ready(function() { $( '#submit' ).click(function( event ) { var nombreVal = $( '#nombre' ).val(); var correoVal = $( '#correo' ).val(); var telefonoVal = $( '#telefono' ).val(); // Para este ejemplo utilizare POST, puedes utilizar mediante GET tambien $.post( 'ActionServlet' , { nombre : nombreVal, correo: correoVal, telefono: telefonoVal }, function(responseText) { $( '#tablaUsuarios' ).html(responseText); }); }); }); </script> <title>Ejemplo AJAX en Java</title> <h1> <u>Insertar Usuario</u></h1> <form id= "form1" > Nombre: <input id= "nombre" type= "text" > Correo: <input id= "correo" type= "text" > Telefono: <input id= "telefono" type= "text" > <input id= "submit" type= "button" value= "Insertar" > </form> <!-- Tabla mostrar los registros --> <div id= "tablaUsuarios" > </div> |
Paso 3: Crear nuestra clase “Usuarios”.
Como hemos dicho la clase la nombraremos “Usuarios”.
A continuación al código de nuestra clase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | public class Usuario { private String nombre; private String correo; private String telefono; // Constructores public Usuario(){ } public Usuario(String nombre, String correo, String telefono) { super(); this .nombre = nombre; this .correo = correo; this .telefono = telefono; } // Propiedades public String getNombre() { return this .nombre; } public void setNombre(String nombre) { this .nombre = nombre; } public String getCorreo() { return this .correo; } public void setCorreo(String correo) { this .correo = correo; } public String getTelefono() { return this .telefono; } public void setTelefono(String telefono) { this .telefono = telefono; } } |
Paso 4: Crear nuestro Servlet y definir la acción.
Añadimos la siguiente clase que he llamado "ActionServlet".
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
public class ActionServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private
ArrayList<Usuario> Usuarios = new ArrayList<Usuario>();
protected void
doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType( "text/html;
charset=iso-8859-1" );
PrintWriter
out = response.getWriter();
// Obtengo los
datos de la peticion
String
nombre = request.getParameter("nombre");
String
correo = request.getParameter("correo");
String
telefono = request.getParameter("telefono");
// Compruebo
que los campos del formulario tienen datos
para añadir a la tabla
if (!nombre.equals("") && !correo.equals("") && !telefono.equals("")) {
// Creo el objeto
persona y lo añado al arrayList
Usuario
usuario = new Usuario(nombre, correo, telefono);
Usuarios.add(usuario);
}
// Mostramos
los datos
out.println("<h3>Lista
Usuarios:</h3>");
out.println("<table
border='1'>");
out.println("<tr>");
out.println("<td>
Nombre </td>");
out.println("<td>
Correo </td>");
out.println("<td>
Telefono </td>");
out.println("</tr>");
for (Usuario usuario : Usuarios){
out.println("<tr>");
out.println("<td>"+usuario.getNombre()+"</td>");
out.println("<td>"+usuario.getCorreo()+"</td>");
out.println("<td>"+usuario.getTelefono()+"</td>");
out.println("</tr>");
}
out.println("</table>");
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | < web-app id = "WebApp_ID" version = "4.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xsi:schemalocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" > < display-name >Ejemplo AJAX</ display-name > < welcome-file-list > < welcome-file >index.html</ welcome-file > < welcome-file >index.htm</ welcome-file > < welcome-file >index.jsp</ welcome-file > < welcome-file >default.html</ welcome-file > < welcome-file >default.htm</ welcome-file > < welcome-file >default.jsp</ welcome-file > </ welcome-file-list > < servlet > < servlet-name >ActionServlet</ servlet-name > < servlet-class >ActionServlet</ servlet-class > </ servlet > < servlet-mapping > < servlet-name >ActionServlet</ servlet-name > < url-pattern >/</ url-pattern > </ servlet-mapping > </ web-app > |
No hay comentarios:
Publicar un comentario