Un CRUD (crear, leer, actualizar y eliminar) aplicación es la aplicación más importante para cualquier proyecto de desarrollo. En Servlet, podemos fácilmente crear aplicación CRUD.
Ejemplo CRUD
Crear un table "crudservlet" en una base de datos MySql con los siguientes campos: id es autoincrementable , name, password, email andycountry.
la base de datos que se uso para esta prueba fue MySQL "prueba" y la tabla "crudservlet":
En las siguientes imágenes veremos el paso a paso del proyecto usando servlet y jsp:
El enlace del proyecto se estará dejando al final de la página:
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Proyecto CRUD</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container-fluid"> <div class="row-fluid"> <div class="col-md-6"> <h4 class="text-center">Agregar Nuevo Empleado</h4> <form action="SaveServlet" method="post"> <div class = "form-group"> <label for="name">Nombre:</label> <input type="text" class="form-control" name="name" /> </div> <div class="form-group"> <label for="password">Contraseña:</label> <input type="password" class="form-control" name="password" /> </div> <div class="form-group"> <label for="email">Correo:</label> <input type="email" class="form-control" name="email" /> </div> <div class="form-group"> <label for="country">País:</label> <select name="country" class="form-control"> <option>India</option> <option>Perú</option> <option>USA</option> <option>UK</option> <option>Other</option> </select> </div> <div class="form-group"> <input type="submit" class="btn btn-success" value="Guardar Empleado" /> </div> </form> <br /> <a href="ViewServlet">ver Empleados</a> </div> </div> </div> </body> </html>
Emp.java
package com.cloudsrcsoft.crud; public class Emp { private int id; private String name, password, email, country; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Override public String toString() { return "Emp [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", country=" + country + "]"; } }
EmpDao.java
package com.cloudsrcsoft.crud; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class EmpDao { private static Connection con = null; public static int save(Emp e) { int status = 0; try { con = DataBase.getDBConnection(); PreparedStatement ps = con.prepareStatement("insert into crudservlet(name,password,email,country) values (?,?,?,?)"); ps.setString(1, e.getName()); ps.setString(2, e.getPassword()); ps.setString(3, e.getEmail()); ps.setString(4, e.getCountry()); status = ps.executeUpdate(); con.close(); } catch (Exception ex) { ex.printStackTrace(); } return status; } public static int update(Emp e) { int status = 0; try { con = DataBase.getDBConnection(); PreparedStatement ps = con.prepareStatement("update crudservlet set name=?,password=?,email=?,country=? where id=?"); ps.setString(1, e.getName()); ps.setString(2, e.getPassword()); ps.setString(3, e.getEmail()); ps.setString(4, e.getCountry()); ps.setInt(5, e.getId()); status = ps.executeUpdate(); con.close(); } catch (Exception ex) { ex.printStackTrace(); } return status; } public static int delete(int id) { int status = 0; try { con = DataBase.getDBConnection(); PreparedStatement ps = con.prepareStatement("delete from crudservlet where id=?"); ps.setInt(1, id); status = ps.executeUpdate(); con.close(); } catch (Exception e) { e.printStackTrace(); } return status; } public static Emp getEmployeeById(int id) { Emp e = new Emp(); try { con = DataBase.getDBConnection(); PreparedStatement ps = con.prepareStatement("select * from crudservlet where id=?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { e.setId(rs.getInt(1)); e.setName(rs.getString(2)); e.setPassword(rs.getString(3)); e.setEmail(rs.getString(4)); e.setCountry(rs.getString(5)); } con.close(); } catch (Exception ex) { ex.printStackTrace(); } return e; } public static List<Emp> getAllEmployees() { List<Emp> list = new ArrayList<Emp>(); try { Connection con = DataBase.getDBConnection(); PreparedStatement ps = con.prepareStatement("select * from crudservlet"); ResultSet rs = ps.executeQuery(); while (rs.next()) { Emp e = new Emp(); e.setId(rs.getInt(1)); e.setName(rs.getString(2)); e.setPassword(rs.getString(3)); e.setEmail(rs.getString(4)); e.setCountry(rs.getString(5)); list.add(e); } con.close(); } catch (Exception e) { e.printStackTrace(); } return list; } public static void main(String[] args) { System.out.println(EmpDao.getAllEmployees()); } }
DataBase.java
package com.cloudsrcsoft.crud;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DataBase {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/prueba";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "";
private static Connection dbConnection = null;
public static Connection getDBConnection() {
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}
SaveServlet.java
package com.cloudsrcsoft.crud; 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; @WebServlet("/SaveServlet") public class SaveServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String name=request.getParameter("name"); String password=request.getParameter("password"); String email=request.getParameter("email"); String country=request.getParameter("country"); Emp e=new Emp(); e.setName(name); e.setPassword(password); e.setEmail(email); e.setCountry(country); int status=EmpDao.save(e); if(status>0){ out.print("<p>Se guardo Correctamente!</p>"); request.getRequestDispatcher("index.jsp").include(request, response); }else{ out.println("No se pudo Guardar"); } out.close(); } }
EditSerlvlet.java
package com.cloudsrcsoft.crud; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/EditServlet") public class EditServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sid=request.getParameter("id"); int id=Integer.parseInt(sid); Emp e=EmpDao.getEmployeeById(id); request.setAttribute("employee", e); RequestDispatcher view = getServletContext().getRequestDispatcher("/editEmployee.jsp"); view.forward(request, response); } }
EditSerlvlet2.java
package com.cloudsrcsoft.crud; 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; @WebServlet("/EditServlet2") public class EditServlet2 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String sid=request.getParameter("id"); int id=Integer.parseInt(sid); String name=request.getParameter("name"); String password=request.getParameter("password"); String email=request.getParameter("email"); String country=request.getParameter("country"); Emp e=new Emp(); e.setId(id); e.setName(name); e.setPassword(password); e.setEmail(email); e.setCountry(country); int status=EmpDao.update(e); if(status>0){ response.sendRedirect("ViewServlet"); }else{ out.println("Sorry! unable to update record"); } out.close(); } }
DeleteServlet.java
package com.cloudsrcsoft.crud; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/DeleteServlet") public class DeleteServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sid=request.getParameter("id"); int id=Integer.parseInt(sid); EmpDao.delete(id); response.sendRedirect("ViewServlet"); } }
ViewServlet.java
package com.cloudsrcsoft.crud; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ViewServlet") public class ViewServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); List<Emp> list=EmpDao.getAllEmployees(); request.setAttribute("lstEmployee", list); RequestDispatcher view = getServletContext().getRequestDispatcher("/viewEmployee.jsp"); view.forward(request,response); } }
Al terminar de codificar obtendremos la siguiente salida:
El proyecto se puede descargar en el siguiente enlace: Click Aquí
El proyecto se puede descargar en el siguiente enlace: Click Aquí
Agregar Nuevo Empleado:
Lista de Empleado:
Editar Empleado:
Buenoo para lo básico me parece que está bien !
ResponderEliminar