The time is passing incredibly fast, I've been again a week without posting anything but I'm busy with programming, in fact I've been working on a small billing system that I plan to add to my portfolio once it's finished, as some of you may know from my previous posts in the community, I try to specialize in Java, using specifically jsp and servlets for the development of web applications.
El tiempo se me esta pasando increiblemente rapido, llevo nuevamente una semana sin publicar nada pero es que me ocupado con el tema de la programación, de hecho estuve trabajando en un pequeño sistema de facturación que pienso añadir a mi portafolio una vez este culminado, como ya algunos deben saber por mis anteriores publicaciones en la comunidad, intento especializarme en Java, usando especificamente jsp y servlets para la elaboración de aplicaciones web. |
---|
Before I showed you the login for this system but it was just hard code, now it is fully functional and is the jsp that is responsible for authorizing the user to use the different modules of the system which by the way were developed using sql statements. I did the whole project based on MVC, because it seems to me a good practice for the development of logic systems, for the views I implemented the latest version of bootstrap in order to reduce the time invested, also, if you ask me it seems to me that you get very good results.
Antes les enseñé el login para este sistema pero era solo codigo duro, ahora es completamente funcional y es el jsp que se encarga de autorizar al usuario a utilizar los diferentes modulos del sistema los cuales por cierto fueron desarrollados mediantes sentencias sql. Todo el proyecto lo hice en base a MVC, pues me parece una buena practica para el desarrollo de sistemas de logica, para las vistas implemente la ultima versión de bootstrap con el fin de reducir el tiempo invertido, además, si me lo preguntan a mi me parece que se obtienen resultados sumamente buenos. |
---|
The system has a maintenance module, this so that the person with access to the system can edit: Customers, employees and products, the system does not have user roles, at least not for now, so all users of the employee type will have the same functions within the system, it is supposed to be intended for a family business, but still is a very good basis to raise a project of greater impact or relevance so to speak, try to the best of my knowledge to make the code as optimal as possible, still at this point where I am I have made some evaluations and feel that I could implement best practices. .. What advice can you give me?
El sistema cuenta con un modulo de mantenimiento, esto para que la persona con acceso al sistema pueda editar: Clientes, empleados y productos, el sistema no cuenta con roles de usuario, al menos no por ahora, así que todos los usuarios del tipo empleado tendrán las mismas funciones dentro del sistema, se supone que es destinado para un negocio familiar, pero aún así es una muy buena base para plantear un proyecto de mayor impacto o relevancia por así decirlo, intente en la medida de mis conocimientos hacer el codigo lo más optimo posible, aún así en este punto en el que me encuentro he hecho algunas evaluaciones y siento que pude implementar mejores practicas... ¿Ustedes que podrian aconsejarme? |
---|
The section to generate sale will be basically the most important operation of the system, but I have not been able to complete it yet because believe me, working with netbeans is a tedious process and there have been more than 10 bugs that I have corrected during all this week... I want to clarify that this is not a complaint, I love programming in java and I am very happy with this project, in fact the module in terms of interface works very well, it generates the total to pay for the whole sale, also the inputs bring the necessary information from the database: In the first box using the customer's Dni I can search his name and in the second using the product identifier I can find the same.
La sección de generar venta sera basicamente el funcionamiento más importante del sistema, pero aún no he podido completarlo pues creanme, trabajar con netbeans es un proceso tedioso y han sido más de 10 bugs que he corregido durante toda esta semana... Quiero aclarar que esto no es una queja, yo amo programar en java y me encuentro muy feliz con este proyecto, de hecho el modulo en cuanto a interfaz funciona muy bien, me genera el total a pagar de toda la venta, además los input traen la información necesaria de la base de datos: En la primera casilla usando el Dni del cliente puedo buscar su nombre y en la segunda usando el identificador del producto puedo encontrar el mismo. |
---|
What should happen, once we complete the sales order by clicking on "Generate sale" it should send the information to the database with all the details of the same, as well as give the option to print everything in a pdf file .... Yes friends, this system is very similar to what you see in super markets or small businesses that use invoice.
¿Qué deberia suceder?, una vez que completamos la orden de venta al dar click en "Generar venta" tendría que enviar la información a la base de datos con todos los detalles de la misma, así mismo dar la opción de imprimir todo en un archivo pdf... Si amigos, este sistema es muy similar a lo que ves en super mercados o pequeños negocios que utilicen factura. |
---|
Clientes.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/68bd6542c8.js" crossorigin="anonymous"></script>
<title>Clientes</title>
</head>
<body>
<div class="d-flex">
<div class="col-sm-8">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>DNI</th>
<th>NOMBRES</th>
<th>DIRECCION</th>
<th>ESTADO</th>
<th>ACCIONES</th>
</tr>
</thead>
<tbody>
<c:forEach var="cl" items="${clientes}">
<tr>
<td>${cl.getId()}</td>
<td>${cl.getDni()}</td>
<td>${cl.getNombres()}</td>
<td>${cl.getDireccion()}</td>
<td>${cl.getEstado()}</td>
<td>
<a style="border: none; font-size: 20px" class="btn btn-outline-dark" href="ServletControlador?menu=Clientes&accion=Editar&id=${cl.getId()}"><i class="fas fa-solid fa-pen-nib"></i>a>
<a style="border: none; font-size: 20px" class="btn btn-outline-dark" href="ServletControlador?menu=Clientes&accion=Eliminar&id=${cl.getId()}"><i class="fas fa-sharp fa-solid fa-trash"></i>a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div class="card col-sm-4 text-center">
<div class="card-body">
<form action="ServletControlador?menu=Clientes" method="POST">
<div class="form-group">
<label>DNI</label>
<input type="text" value="${cliente.getDni()}" name="txtDniC" class="form-control"/>
</div>
<div class="form-group">
<label>NOMBRE</label>
<input type="text" value="${cliente.getNombres()}" name="txtNombresC" class="form-control"/>
</div>
<div class="form-group">
<label>DIRECCION</label>
<input type="text" value="${cliente.getDireccion()}"name="txtDireccionC" class="form-control"/>
</div>
<div class="form-group">
<label>ESTADO</label>
<input type="text" value="${cliente.getEstado()}"name="txtEstadoC" class="form-control"/>
</div>
<input type="submit" name="accion" value="Agregar" class="btn btn-dark"/>
<input type="submit" name="accion" value="Actualizar" class="btn btn-secondary"/>
</form>
</div>
</div>
</div>

Empleado.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/68bd6542c8.js" crossorigin="anonymous"></script>
<title>Empleados</title>
</head>
<body>
<div class="d-flex">
<div class="card col-sm-4 text-center" >
<div class="card-body">
<form action="ServletControlador?menu=Empleado" method="POST">
<div class="form-group">
<label>LLAVE</label>
<input type="text" value="${empleado.getDni()}" name="txtDni" class="form-control"/>
</div>
<div class="form-group">
<label>NOMBRE</label>
<input type="text" value="${empleado.getNombres()}" name="txtNombres" class="form-control"/>
</div>
<div class="form-group">
<label>TELEFONO</label>
<input type="text" value="${empleado.getTelefono()}"name="txtTelefono" class="form-control"/>
</div>
<div class="form-group">
<label>ESTADO</label>
<input type="text" value="${empleado.getEstado()}"name="txtEstado" class="form-control"/>
</div>
<div class="form-group">
<label>USUARIO</label>
<input type="text" value="${empleado.getUser()}" name="txtUsuario" class="form-control"/>
</div>
<input type="submit" name="accion" value="Agregar" class="btn btn-dark"/>
<input type="submit" name="accion" value="Actualizar" class="btn btn-secondary"/>
</form>
</div>
</div>
<div class="col-sm-8">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>LLAVE</th>
<th>NOMBRES</th>
<th>TELEFONO</th>
<th>ESTADO</th>
<th>USUARIO</th>
<th>ACCIONES</th>
</tr>
</thead>
<tbody>
<c:forEach var="em" items="${empleados}">
<tr>
<td>${em.getId()}</td>
<td>${em.getDni()}</td>
<td>${em.getNombres()}</td>
<td>${em.getTelefono()}</td>
<td>${em.getEstado()}</td>
<td>${em.getUser()}</td>
<td>
<a style="border: none; font-size: 20px" class="btn btn-outline-dark" href="ServletControlador?menu=Empleado&accion=Editar&id=${em.getId()}"><i class="fas fa-solid fa-pen-nib"></i>a>
<a style="border: none; font-size: 20px" class="btn btn-outline-dark" href="ServletControlador?menu=Empleado&accion=Eliminar&id=${em.getId()}"><i class="fas fa-sharp fa-solid fa-trash"></i>a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</body>
</html>

Principal.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/68bd6542c8.js" crossorigin="anonymous"></script>
<jsp:include page="WEB-INF/vistas/principal/navbar.jsp"/>
<jsp:include page="WEB-INF/vistas/principal/dropdown.jsp"/>
<div class="m-4" style="height: 550px">
<iframe name="myFrame"style="border: none;height: 100%; width: 100%"> </iframe>
</div>
<jsp:include page="WEB-INF/vistas/comunes/piePagina.jsp"/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

Producto.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/68bd6542c8.js" crossorigin="anonymous"></script>
<title>Productos</title>
</head>
<body>
<button type="button" class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#agregarProducto">
<i class="fas fa-solid fa-plus"></i> Agregar nuevo producto
</button>
<br> <br>
<div class="modal fade" id="agregarProducto" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header text-center">
<h3 class="modal-title fs-5" id="exampleModalLabel">Agregar un nuevo producto</h3>
<button type="button" class="btn btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="ServletControlador?menu=Producto" method="POST">
<div class="form-group">
<label>NOMBRES</label>
<input type="text" value="" name="txtNombres" class="form-control"/>
</div>
<div class="form-group">
<label>PRECIO</label>
<input type="text" value="" name="txtPrecio" class="form-control"/>
</div>
<div class="form-group">
<label>STOCK</label>
<input type="text" value=""name="txtStock" class="form-control"/>
</div>
<div class="form-group">
<label>ESTADO</label>
<input type="text" value=""name="txtEstado" class="form-control"/>
</div>
<input type="submit" name="accion" value="Agregar" class="btn btn-dark"/>
</form>
</div>
</div>
</div>
</div>
<div class="col-sm-13 mx-auto">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>NOMBRES</th>
<th>PRECIO</th>
<th>STOCK</th>
<th>ESTADO</th>
<th>ACCIONES</th>
</tr>
</thead>
<tbody>
<c:forEach var="pt" items="${productos}">
<tr>
<td>${pt.getId()}</td>
<td>${pt.getNombre()}</td>
<td>${pt.getPrecio()}</td>
<td>${pt.getStock()}</td>
<td>${pt.getEstado()}</td>
<td>
<a style="border: none; font-size: 20px" class="btn btn-outline-dark" href="ServletControlador?menu=Producto&accion=Editar&id=${pt.getId()}"><i class="fas fa-solid fa-pen-nib"></i>a>
<a style="border: none; font-size: 20px" class="btn btn-outline-dark" href="ServletControlador?menu=Producto&accion=Eliminar&id=${pt.getId()}"><i class="fas fa-sharp fa-solid fa-trash"></i>a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</html>

registrarVenta.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/68bd6542c8.js" crossorigin="anonymous"></script>
<title>Registrar Venta</title>
</head>
<body>
<div class="d-flex">
<div class="col-sm-4">
<div class="card">
<form action="ServletControlador?menu=RegistrarVenta" method="POST">
<div class="card-body">
<div class="form-group">
<label>Datos del cliente</label>
</div>
<div class="form-group d-flex">
<div class="col-sm-7 d-flex">
<input type="text" name="codigoCliente" value="${c.getDni()}" class="form-control" placeholder="Codigo"/>
<input type="submit" name="accion" value="BuscarCliente" class="btn btn-outline-dark"/>
</div>
<div class="col-sm-6">
<input type="text" name="nombresCliente" value="${c.getNombres()}" class="form-control"/>
</div>
</div>
<div class="form-group">
<label>Datos de producto</label>
</div>
<div class="form-group d-flex">
<div class="col-sm-7 d-flex">
<input type="text" name="codigoProducto" class="form-control" placeholder="Codigo"/>
<input type="submit" name="accion" value="BuscarProducto" class="btn btn-outline-dark"/>
</div>
<div class="col-sm-6">
<input type="text" name="nombresProducto" value="${producto.getNombre()}"class="form-control"/>
</div>
</div>
<div class="form-group d-flex">
<div class="col-sm-7 d-flex">
<input type="text" name="precio" value="${producto.getPrecio()}" class="form-control" placeholder="$/0.00"/>
</div>
<div class="col-sm-3">
<input type="number" name="cantidad" value="1" class="form-control"/>
</div>
<div class="col-sm-3">
<input type="text" name="stock" value="${producto.getStock()}" placeholder="Stock" class="form-control"/>
</div>
</div>
<div class="form-group">
<input type="submit" name="accion" value="Agregar" class="btn btn-dark"/>
</div>
</div>
</form>
</div>
</div>
<div class="col-sm-8">
<div class="card">
<div class="card-body">
<div class="d-flex col-sm-4 ml-auto">
<i style="font-size: 20px"class="fas fa-solid fa-magnifying-glass"></i>
<input type="text" name="nSerie" value="${nserie}" class="form-control"/>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>N°</th>
<th>Codigo</th>
<th>Descripcion</th>
<th>Precio</th>
<th>Cantidad</th>
<th>Total</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<c:forEach var="list" items="${lista}">
<tr>
<td>${list.getItem()}</td>
<td>${list.getId_producto()}</td>
<td>${list.getdProducto()}</td>
<td>${list.getPrecio()}</td>
<td>${list.getCantidad()}</td>
<td>${list.getTotal()}</td>
<td style="color:white">
<a class="btn btn-dark">Editar</a>
<a class="btn btn-secondary">Eliminar</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div class="card-footer d-flex">
<div class="col-sm-6">
<a href="ServletControlador?menu=RegistrarVenta&accion=GenerarVenta" class="btn btn-dark">Generar Venta</a>
<input type="submit" name="accion" value="Cancelar" class="btn btn-secondary"/>
</div>
<div class="col-sm-4 ml-auto">
<input type="text" nombre="txtTotal" value="$${totalpagar}" class="form-control"/>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

ServletControlador.java

package Controlador;
import Config.GenerarSerie;
import Modelo.Cliente;
import Modelo.ClienteDAO;
import Modelo.Empleado;
import Modelo.EmpleadoDAO;
import Modelo.Producto;
import Modelo.ProductoDAO;
import Modelo.Venta;
import Modelo.VentaDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletControlador extends HttpServlet {
// Variables para los metodos de empleado
Empleado em = new Empleado();
EmpleadoDAO edao = new EmpleadoDAO();
int idE;
//Variables para los metodos de cliente
Cliente cl = new Cliente();
ClienteDAO cdao = new ClienteDAO();
int idC;
//Variables para los metodos de producto
Producto pt = new Producto();
ProductoDAO pdao = new ProductoDAO();
int idP;
//Variables para metodos de registrar venta
Venta v = new Venta();
List<Venta> lista = new ArrayList<>();
int item;
int cod;
String dProducto;
double precio;
int cant;
double total;
double totalPagar;
VentaDAO vdao = new VentaDAO();
//Variables para metodos de generar número de serie
String numeroserie;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String menu = request.getParameter("menu");
String accion = request.getParameter("accion");
if (menu.equals("Principal")) {
request.getRequestDispatcher("Principal.jsp").forward(request, response);
}
if (menu.equals("Empleado")) {
switch (accion) {
case "Listar":
List lista = edao.listar();
request.setAttribute("empleados", lista);
break;
case "Agregar":
String dni = request.getParameter("txtDni");
String nom = request.getParameter("txtNombres");
String tel = request.getParameter("txtTelefono");
String est = request.getParameter("txtEstado");
String usr = request.getParameter("txtUsuario");
em.setDni(dni);
em.setNombres(nom);
em.setTelefono(tel);
em.setEstado(est);
em.setUser(usr);
edao.agregar(em);
request.getRequestDispatcher("ServletControlador?menu=Empleado&accion=Listar").forward(request, response);
break;
case "Editar":
idE = Integer.parseInt(request.getParameter("id"));
Empleado e = edao.listarId(idE);
request.setAttribute("empleado", e);
request.getRequestDispatcher("ServletControlador?menu=Empleado&accion=Listar").forward(request, response);
break;
case "Actualizar":
String dniA = request.getParameter("txtDni");
String nomA = request.getParameter("txtNombres");
String telA = request.getParameter("txtTelefono");
String estA = request.getParameter("txtEstado");
String usrA = request.getParameter("txtUsuario");
em.setDni(dniA);
em.setNombres(nomA);
em.setTelefono(telA);
em.setEstado(estA);
em.setUser(usrA);
em.setId(idE);
edao.actualizar(em);
request.getRequestDispatcher("ServletControlador?menu=Empleado&accion=Listar").forward(request, response);
break;
case "Eliminar":
idE = Integer.parseInt(request.getParameter("id"));
edao.delete(idE);
request.getRequestDispatcher("ServletControlador?menu=Empleado&accion=Listar").forward(request, response);
break;
default:
throw new AssertionError();
}
request.getRequestDispatcher("Empleado.jsp").forward(request, response);
}
if (menu.equals("Clientes")) {
switch (accion) {
case "Listar":
List lista = cdao.listar();
request.setAttribute("clientes", lista);
break;
case "Agregar":
String dni = request.getParameter("txtDniC");
String nom = request.getParameter("txtNombresC");
String drc = request.getParameter("txtDireccionC");
String est = request.getParameter("txtEstadoC");
cl.setDni(dni);
cl.setNombres(nom);
cl.setDireccion(drc);
cl.setEstado(est);
cdao.agregar(cl);
request.getRequestDispatcher("ServletControlador?menu=Clientes&accion=Listar").forward(request, response);
break;
case "Actualizar":
String dniC = request.getParameter("txtDniC");
String nomC = request.getParameter("txtNombresC");
String drcC = request.getParameter("txtDireccionC");
String estC = request.getParameter("txtEstadoC");
cl.setDni(dniC);
cl.setNombres(nomC);
cl.setDireccion(drcC);
cl.setEstado(estC);
cl.setId(idC);
cdao.actualizar(cl);
request.getRequestDispatcher("ServletControlador?menu=Clientes&accion=Listar").forward(request, response);
break;
case "Editar":
idC = Integer.parseInt(request.getParameter("id"));
Cliente c = cdao.listarId(idC);
request.setAttribute("cliente", c);
request.getRequestDispatcher("ServletControlador?menu=Clientes&accion=Listar").forward(request, response);
break;
case "Eliminar":
idC = Integer.parseInt(request.getParameter("id"));
cdao.delete(idC);
request.getRequestDispatcher("ServletControlador?menu=Clientes&accion=Listar").forward(request, response);
break;
default:
throw new AssertionError();
}
request.getRequestDispatcher("Clientes.jsp").forward(request, response);
}
if (menu.equals("Producto")) {
switch (accion) {
case "Listar":
List lista = pdao.listar();
request.setAttribute("productos", lista);
break;
case "Agregar":
String nom = request.getParameter("txtNombres");
String prc = request.getParameter("txtPrecio");
String stk = request.getParameter("txtStock");
String est = request.getParameter("txtEstado");
pt.setNombre(nom);
pt.setPrecio(Double.parseDouble(prc));
pt.setStock(Integer.parseInt(stk));
pt.setEstado(est);
pdao.agregar(pt);
request.getRequestDispatcher("ServletControlador?menu=Producto&accion=Listar").forward(request, response);
break;
case "Actualizar":
String nomP = request.getParameter("txtNombres");
String prcP = request.getParameter("txtPrecio");
String stkP = request.getParameter("txtStock");
String estP = request.getParameter("txtEstado");
pt.setNombre(nomP);
pt.setPrecio(Double.parseDouble(prcP));
pt.setStock(Integer.parseInt(stkP));
pt.setEstado(estP);
pt.setId(idP);
pdao.actualizar(pt);
request.getRequestDispatcher("ServletControlador?menu=Producto&accion=Listar").forward(request, response);
break;
case "Editar":
idP = Integer.parseInt(request.getParameter("id"));
Producto p = pdao.listarId(idP);
request.setAttribute("producto", p);
String jspEditarProducto = "/WEB-INF/vistas/producto/editProducto.jsp";
request.getRequestDispatcher(jspEditarProducto).forward(request, response);
break;
case "Eliminar":
idP = Integer.parseInt(request.getParameter("id"));
pdao.delete(idP);
request.getRequestDispatcher("ServletControlador?menu=Producto&accion=Listar").forward(request, response);
break;
default:
throw new AssertionError();
}
request.getRequestDispatcher("Producto.jsp").forward(request, response);
}
if (menu.equals("RegistrarVenta")) {
switch (accion) {
case "BuscarCliente":
String dni = request.getParameter("codigoCliente");
cl.setDni(dni);
cl = cdao.buscar(dni);
request.setAttribute("lista", lista);
request.setAttribute("c", cl);
request.setAttribute("nserie", numeroserie);
break;
case "BuscarProducto":
int id = Integer.parseInt(request.getParameter("codigoProducto"));
pt = pdao.listarId(id);
request.setAttribute("c", cl);
request.setAttribute("lista", lista);
request.setAttribute("producto", pt);
request.setAttribute("totalpagar", totalPagar);
request.setAttribute("nserie", numeroserie);
break;
case "Agregar":
totalPagar = 0.0;
item = item+1;
cod=pt.getId();
dProducto = request.getParameter("nombresProducto");
precio = Double.parseDouble(request.getParameter("precio"));
cant = Integer.parseInt(request.getParameter("cantidad"));
total = precio * cant;
v = new Venta();
v.setItem(item);
v.setId(cod);
v.setdProducto(dProducto);
v.setPrecio(precio);
v.setCantidad(cant);
v.setTotal(total);
lista.add(v);
for(int i = 0; i < lista.size(); i++){
totalPagar = totalPagar + lista.get(i).getTotal();
}
request.setAttribute("nserie", numeroserie);
request.setAttribute("totalpagar", totalPagar);
request.setAttribute("lista", lista);
request.setAttribute("c", cl);
break;
case "GenerarVenta":
v.setId_cliente(cl.getId());
v.setNumSerie(numeroserie);
v.setFecha("2020-12-12");
v.setMonto(totalPagar);
v.setEstado("1");
vdao.guardarVenta(v);
//Guardar detalle de la venta
int idv = Integer.parseInt(vdao.idVentas());
for (int i = 0; i < lista.size(); i++) {
v = new Venta();
v.setId(idv);
v.setId(lista.get(i).getId_producto());
v.setCantidad(lista.get(i).getCantidad());
v.setPrecio(lista.get(i).getPrecio());
vdao.guardarDetalleVenta(v);
}
break;
default:
numeroserie = vdao.generarSerie();
if(numeroserie.isEmpty()){
numeroserie = "00000001";
request.setAttribute("nserie", numeroserie);
}else{
int incrementar = Integer.parseInt(numeroserie);
GenerarSerie gs = new GenerarSerie();
numeroserie = gs.NumeroSerie(incrementar);
request.setAttribute("nserie", numeroserie);
}
request.getRequestDispatcher("RegistrarVenta.jsp").forward(request, response);
}
request.getRequestDispatcher("RegistrarVenta.jsp").forward(request, response);
}
}
//
/**
* Handles the HTTP GET
method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP POST
method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}//
}

Validar.java

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template
*/
package Controlador;
import Modelo.Empleado;
import Modelo.EmpleadoDAO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Emamuel
*/
public class Validar extends HttpServlet {
EmpleadoDAO edao = new EmpleadoDAO();
Empleado em = new Empleado();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try ( PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("");
out.println("");
out.println("");
out.println("Servlet Validar");
out.println("");
out.println("");
out.println("Servlet Validar at " + request.getContextPath() + "");
out.println("");
out.println("");
}
}
//
/**
* Handles the HTTP GET
method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP POST
method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String accion = request.getParameter("accion");
if(accion.equalsIgnoreCase("ingresar")){
String user = request.getParameter("txtUser");
String pass = request.getParameter("txtPass");
em = edao.validar(user, pass);
if(em.getUser() != null){
request.setAttribute("usuario", em);
request.getRequestDispatcher("ServletControlador?menu=Principal").forward(request, response);
}else{
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
else{
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}//
}

Cliente.java

package Modelo;
public class Cliente {
int id;
String dni;
String nombres;
String direccion;
String estado;
public Cliente() {
}
public Cliente(int id, String dni, String nombres, String direccion, String estado) {
this.id = id;
this.dni = dni;
this.nombres = nombres;
this.direccion = direccion;
this.estado = estado;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}

ClienteDAO.java

package Modelo;
import Config.Conexion;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class ClienteDAO {
Conexion cn = new Conexion();
Connection con;
PreparedStatement stmt;
ResultSet rs;
int r;
public Cliente buscar(String dni){
Cliente c = new Cliente();
String sql = "select * from cliente where Dni="+dni;
try {
con = cn.Conexion();
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
while(rs.next()){
c.setId(rs.getInt(1));
c.setDni(rs.getString(2));
c.setNombres(rs.getString(3));
c.setDireccion(rs.getString(4));
c.setEstado(rs.getString(5));
}
} catch (Exception e) {
}
return c;
}
//CRUD
public List listar(){
String sql = "select * from cliente";
List<Cliente> lista = new ArrayList<>();
try {
con = cn.Conexion();
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
while(rs.next()){
Cliente cl = new Cliente();
cl.setId(rs.getInt(1));
cl.setDni(rs.getString(2));
cl.setNombres(rs.getString(3));
cl.setDireccion(rs.getString(4));
cl.setEstado(rs.getString(5));
lista.add(cl);
}
} catch (Exception e) {
}
return lista;
}
public int agregar(Cliente cl){
String sql = "insert into cliente(Dni, Nombres, Direccion, Estado)values(?, ?, ?, ?)";
try {
con = cn.Conexion();
stmt = con.prepareStatement(sql);
stmt.setString(1, cl.getDni());
stmt.setString(2, cl.getNombres());
stmt.setString(3, cl.getDireccion());
stmt.setString(4, cl.getEstado());
stmt.executeUpdate();
} catch (Exception e) {
}
return r;
}
public Cliente listarId(int id){
Cliente clt = new Cliente();
String sql = "select * from cliente where IdCliente="+id;
try {
con = cn.Conexion();
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
while(rs.next()){
clt.setDni(rs.getString(2));
clt.setNombres(rs.getString(3));
clt.setDireccion(rs.getString(4));
clt.setEstado(rs.getString(5));
}
} catch (Exception e) {
}
return clt;
}
public int actualizar(Cliente cl){
String sql = "update cliente set Dni=?, Nombres=?, Direccion=?, Estado=? where IdCliente=?";
try {
con = cn.Conexion();
stmt = con.prepareStatement(sql);
stmt.setString(1, cl.getDni());
stmt.setString(2, cl.getNombres());
stmt.setString(3, cl.getDireccion());
stmt.setString(4, cl.getEstado());
stmt.setInt(5, cl.getId());
stmt.executeUpdate();
} catch (Exception e) {
}
return r;
}
public void delete(int id){
String sql = "delete from cliente where IdCliente="+id;
try {
con = cn.Conexion();
stmt = con.prepareStatement(sql);
stmt.executeUpdate();
} catch (Exception e) {
}
}
}