www.posse.ueg.br Home Page: http://www.posse.ueg.br/index.php/conexao-ueg/meuperfil/userprofile/ronaldo Dado o diagrama de classe abaixo: Lista de exercícios I - RESPOSTAS Servlets e banco de dados 1. Crie um banco de dados e as tabelas para armazenar as classes acima. CREATE TABLE `cliente` ( `id` INTEGER(11) NOT NULL AUTO_INCREMENT, `nome` VARCHAR(70) COLLATE latin1_swedish_ci NOT NULL DEFAULT '', `documento` VARCHAR(30) COLLATE latin1_swedish_ci NOT NULL DEFAULT '', `ativo` ENUM('S','N') COLLATE latin1_swedish_ci DEFAULT 'S', PRIMARY KEY USING BTREE (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 CHARACTER SET 'latin1' COLLATE 'latin1_swedish_ci' COMMENT='InnoDB free: 7168 Kb; CREATE TABLE `pedido` ( `id` INTEGER(11) NOT NULL, `data` DATE NOT NULL, `id_cliente` INTEGER(11) NOT NULL, `valor` DOUBLE(10,2) DEFAULT NULL, PRIMARY KEY USING BTREE (`id`), KEY `id_cliente` USING BTREE (`id_cliente`), CONSTRAINT `pedido_fk1` FOREIGN KEY (`id_cliente`) REFERENCES `cliente` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE ) ENGINE=InnoDB CHARACTER SET 'latin1' COLLATE 'latin1_swedish_ci' COMMENT='InnoDB free: 7168 kb; (`id_cliente`) REFER `venda/cliente`(`id`) ON DELETE NO AC'; 2. Utilizando o padrão Connection Factory crie uma classe para conectar ao banco dados conforme os dados abaixo: a. Servidor: localhost b. Nome: venda
c. Usuário: <<conforme configuração do banco>> d. Senha: <<conforme configuração do banco>> package br.ueg.posse.db; import java.sql.connection; import java.sql.drivermanager; public class Database { public static Connection getconexao() throws SQLException{ try { Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection("jdbc:mysql://localhost:3306/venda?user=root&password="); catch (ClassNotFoundException e) { e.printstacktrace(); return null; 3. Utilizando a linguagem Java, crie o modelo para representar a classe Cliente. package br.ueg.posse.modelo; public class Cliente { private Integer id; private String nome; private String documento; private Double saldo; private Ativo ativo; public Integer getid() { return id; public void setid(integer id) { this.id = id; public String getnome() { return nome; public void setnome(string nome) { this.nome = nome; public String getdocumento() { return documento; public void setdocumento(string documento) { this.documento = documento; public Double getsaldo() { return saldo; public void setsaldo(double saldo) { this.saldo = saldo; public Ativo getativo() { return ativo; public void setativo(ativo ativo) { this.ativo = ativo;
4. Utilizando a linguagem Java, e o padrão DAO (Data Access Object), crie uma classe com os métodos descritos no diagrama de classes Cliente. package br.ueg.posse.dao; import java.sql.connection; import java.sql.preparedstatement; import br.ueg.posse.db.database; import br.ueg.posse.modelo.cliente; public class ClienteDAO { private Connection conexao; public ClienteDAO() throws SQLException { conexao = Database.getConexao(); public void incluir(cliente cliente) throws SQLException{ String sql = "INSERT INTO cliente (nome,documento,saldo,ativo)" + "values(?,?,?,?)"; stmt.setstring(1, cliente.getnome()); stmt.setstring(2, cliente.getdocumento()); stmt.setdouble(3, cliente.getsaldo()); stmt.setstring(4, cliente.getativo().name()); public void excluir(cliente cliente) throws SQLException{ String sql = "DELETE cliente WHERE id=?"; stmt.setint(1, cliente.getid()); public void alterar(cliente cliente) throws SQLException{ String sql = "UPDATE cliente SET (nome=?, documento=?, saldo=?, ativo=?) WHERE id=?"; stmt.setstring(1, cliente.getnome()); stmt.setstring(2, cliente.getdocumento()); stmt.setdouble(3, cliente.getsaldo()); stmt.setstring(4, cliente.getativo().name()); stmt.setint(5, cliente.getid()); 5. Crie um formulário HTML que possibilite ao usuário informar os dados do Cliente, conforme representação no diagrama de classes <!DOCTYPE html> <html> <head> <meta charset="iso-8859-1"> <title>cadastro de Clientes</title> </head> <body>
<form action="clienteservlet" method="get"> <label>nome:</label> <input type="text" name="nome" id="nome"/><br> <label>documento:</label> <input type="text" name="documento" id="documento"/><br> <label>saldo:</label> <input type="text" nama="saldo" id="saldo"/><br> <label>ativo?:</label> <select name="ativo" id="ativo"> <option value="s">sim</option> <option value="n">não</option> </select> <br> <input type="submit" value="gravar dados"/> </form> </body> </html> 6. Crie um servlet que possibilite a inserção dos dados do formulário na tabela do banco de dados. package br.ueg.posse.servlet; 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; import br.ueg.posse.dao.clientedao; import br.ueg.posse.modelo.ativo; import br.ueg.posse.modelo.cliente; @WebServlet("/ClienteServlet") public class ClienteServlet extends HttpServlet { private static final long serialversionuid = 1L; protected void service(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { String nome = request.getparameter("nome"); String documento = request.getparameter("documento"); String saldo = request.getparameter("saldo"); String ativo = request.getparameter("ativo"); Cliente cliente = new Cliente(); cliente.setnome(nome); cliente.setdocumento(documento); cliente.setsaldo(double.parsedouble(saldo)); if (ativo.equals("s")){ cliente.setativo(ativo.valueof("s")); else{ cliente.setativo(ativo.valueof("n")); try { ClienteDAO dao = new ClienteDAO(); dao.incluir(cliente); catch (SQLException e) {
System.out.println("Erro ao inserir o registro no banco de dados: "+e.getmessage()); e.printstacktrace();