0% found this document useful (0 votes)
38 views17 pages

Ejercicio Internacional Preguntas

The document contains code for a Java class called Marca that defines methods for retrieving, adding, modifying, and deleting brand records from a database. It also includes code for a servlet called sr_marca that handles requests to perform CRUD operations on Marca objects and redirects to the index page. The index page displays brands in a table and allows adding new brands by popping up a modal form.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views17 pages

Ejercicio Internacional Preguntas

The document contains code for a Java class called Marca that defines methods for retrieving, adding, modifying, and deleting brand records from a database. It also includes code for a servlet called sr_marca that handles requests to perform CRUD operations on Marca objects and redirects to the index page. The index page displays brands in a table and allows adding new brands by popping up a modal form.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

CLASE Marcas

/*

* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license

* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template

*/

package modelo;

import java.sql.ResultSet;

import java.util.HashMap;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import javax.swing.table.DefaultTableModel;

/**

/**

* @author User

*/

public class Marca {

private int id;

private String marca;

private Conexion cn;

public Marca(){

public Marca(int id, String marca) {

this.id = id;

this.marca = marca;

}
public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getMarca() {

return marca;

public void setMarca(String marca) {

this.marca = marca;

public DefaultTableModel leer(){

DefaultTableModel tabla = new DefaultTableModel();

try{

cn= new Conexion();

cn.abrirConexion();

String query ="SELECT e.id_marcas as id, e.marcas FROM marcas as e;";

ResultSet consulta= cn.conexionBD.createStatement().executeQuery(query);

String encabezado [] = {"id","Marcas"};

tabla.setColumnIdentifiers(encabezado);

String datos [] = new String [2];

while(consulta.next()){
datos[0] = consulta.getString("id");

datos[1] = consulta.getString("marcas");

tabla.addRow(datos);

cn.cerrarConexion();

} catch(SQLException ex){

System.out.println(ex.getMessage());

return tabla;

public int agregar (){

int retorno =0;

try{

PreparedStatement parametro;

cn = new Conexion();

String query = "INSERT INTO marcas(marcas) VALUES(?);";

cn.abrirConexion();

parametro = (PreparedStatement)cn.conexionBD.prepareStatement(query);

parametro.setString(1, getMarca());

retorno = parametro.executeUpdate();

cn.cerrarConexion();

}catch(SQLException ex){

System.out.println(ex.getMessage());

retorno = 0;

return retorno;
}

public int modificar (){

int retorno =0;

try{

PreparedStatement parametro;

cn = new Conexion();

String query = "UPDATE marcas SET marcas = ? WHERE id_marcas = ?;";

cn.abrirConexion();

parametro = (PreparedStatement)cn.conexionBD.prepareStatement(query);

parametro.setString(1, getMarca());

parametro.setInt(2, getId());

retorno = parametro.executeUpdate();

cn.cerrarConexion();

}catch(SQLException ex){

System.out.println(ex.getMessage());

retorno = 0;

return retorno;

public int eliminar (){

int retorno =0;

try{

PreparedStatement parametro;

cn = new Conexion();

String query = "DELETE FROM marcas WHERE id_marcas = ?;";

cn.abrirConexion();
parametro = (PreparedStatement)cn.conexionBD.prepareStatement(query);

parametro.setInt(1, getId());

retorno = parametro.executeUpdate();

cn.cerrarConexion();

}catch(SQLException ex){

System.out.println(ex.getMessage());

retorno = 0;

return retorno;

public int mostrar (){return 0;}

CONTROLADOR sr_marca

/*

* 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 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;

import modelo.Marca;
/**

* @author User

*/

public class sr_marca extends HttpServlet {

/**

* Processes requests for both HTTP <code>GET</code> and <code>POST</code>

* methods.

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

Marca marca;

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("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");

out.println("<title>Servlet sr_marca</title>");

out.println("</head>");

out.println("<body>");

marca = new Marca(Integer.valueOf(request.getParameter("txt_id")),


request.getParameter("txt_marca"));
if("agregar".equals(request.getParameter("btn_agregar"))){

if (marca.agregar() > 0) {

response.sendRedirect("index.jsp");

}else{

out.println("<h1> Error .... </h1>");

if("modificar".equals(request.getParameter("btn_modificar"))){

if (marca.modificar() > 0) {

response.sendRedirect("index.jsp");

}else{

out.println("<h1> Error .... </h1>");

if("eliminar".equals(request.getParameter("btn_eliminar"))){

if (marca.eliminar() > 0) {

response.sendRedirect("index.jsp");

}else{

out.println("<h1> Error .... </h1>");

}
}

out.println("</body>");

out.println("</html>");

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to


edit the code.">

/**

* Handles the HTTP <code>GET</code> 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 <code>POST</code> 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";

}// </editor-fold>

Index

<%@page import="modelo.Marca" %>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@page import="java.util.HashMap" %>

<%@page import="javax.swing.table.DefaultTableModel" %>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Marcas</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">

</head>

<body>

<h1><center>Formulario Marcas</center></h1>

<div class="container">

<div class="modal fade" id="modal_marcas" role="dialog">

<div class="modal-dialog">

<!-- Modal content-->

<div class="modal-content">

<div class="modal-body">

<form action="sr_marca" method="post" class="form-group">

<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">

<center>

<br>

<label for="lbl_id"><b>ID</b></label>

<input type="text" name="txt_id" id="txt_id" class="form-control" value="0" readonly>

<label for="lbl_marcas"><b>Nombres de la Marca:</b></label>


<input type="text" name="txt_marca" id="txt_marca" class="form-control" placeholder
="Ejemplo: marca1 marca2 " required>

<br>

<br>

<button name="btn_agregar" id="btn_agregar" value="agregar" class="btn btn-primary btn-


lg">Agregar</button>

<button name="btn_modificar" id="btn_modificar" value="modificar" class="btn btn-success


btn-lg">Modificar</button>

<button name="btn_eliminar" id="btn_modificar" value="eliminar" class="btn btn-danger btn-


lg" onclick="javascript:if(!confirm('¿Desea Eliminar El Registro?'))return false" >Eliminar</button>

<button type="button" class="btn btn-warning btn-lg"


data-dismiss="modal">Regresar</button>

</form>

</div>

</div>

</div>

</div>

</div>

<table class="table table-striped">

<thead>

<tr>
<th>Marcas</th>

</tr>

</thead>

<tbody id="tbl_marcas">

<center>

<%

Marca marca = new Marca();

DefaultTableModel tabla = new DefaultTableModel();

tabla = marca.leer();

for(int t=0; t<tabla.getRowCount();t++){

out.println("<tr data-id="+tabla.getValueAt(t, 0)+">");

out.println("<td>"+tabla.getValueAt(t, 1)+"</td>");

out.println("</tr>");

%>

</center>

</tbody>

</table>

<center> <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-


target="#modal_marcas">Nuevo</button>

<button type="button" class="btn btn-warning btn-lg" data-dismiss="modal">Regresar</button>

</center>

</center>

</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

<script type="text/javascript">

$('#tbl_marcas').on('click', 'tr', function (event) {

var target = $(event.currentTarget);

var id = target.data('id');

var marca = target.find("td").eq(0).text();

$("#txt_id").val(id);

$("#txt_marca").val(marca);

$("#modal_marcas").modal('show');

});

</script>

</body>

</html>

Conexión

* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license

* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template

*/
package modelo;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import javax.swing.*;

/**

* @author User

*/

public class Conexion {

Connection conexionBD;

public final String bd = "db_pruebas";

public final String usuario = "usr_ana";

public final String clave = "ana123";

public final String urlConexion = String.format("jdbc:mysql://localhost:3306/%s",bd);

public final String jdbc = "com.mysql.cj.jdbc.Driver";

public void abrirConexion(){

try{

Class.forName(jdbc);

this.conexionBD = DriverManager.getConnection(urlConexion, usuario, clave);

}catch(ClassNotFoundException | SQLException e){

JOptionPane.showMessageDialog(null, "No se ha conectado a la base de datos " +


e.getMessage());

public void cerrarConexion(){

try{

this.conexionBD.close();

}catch(SQLException e){
JOptionPane.showMessageDialog(null, "Error " + e.getMessage());

Puertos

Funcionamiento

You might also like