JavaBeans é a tecnologia Java que lhe permite escrever programas Java e convertê-los em Beans que poderão ser utilizados por programadores em suas atividades de desenvolvimento de aplicativos.
Uma vez que você tenha criado um bean, os usuários de qualquer ambiente compatível com a tecnologia JavaBeans podem usá-lo prontamente.
Primeiro exercício:
Os programas necessários para realizar os exercícios abaixo são:
Sessão09App
Nesse exercício iremos gerar um relatório através do clique de um botão. Veja o layout abaixo:
Ao se clicar no botão gerar relatório a seguinte tela será mostrada:
Para montarmos o formulário com o botão devemos clicar com o botão direito do mouse em cima do pacote visão e em new JFrame e depois é só arrastar o botão para o JFrame:
Precisamos gerar um relatório no software jaspersoft ireport designer:
Clique em arquivo new, faça as configurações de conexão com o BD, usuário e senha.
Selecione o layout do relatório desejado, ao se clicar no botão step 2:
Clique no botão launch report wizard:
Digite a query select * from....
Adicione os campos para a coluna da direita:
Clique em next, next...
Clique no botão preview:
Pronto agora é só jogar o arquivo gerado teste4.jasper dentro da pasta conforme figura abaixo.
O botão preview irá mostrar como irá ficar a página de relatório. Voltando para o netbeans temos que configurar o seguinte atributo em propriedades:
O resultado será:
O código é:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- /**
- *
- * @author paulo983
- */
- public class ExemploButtonRelatorio extends javax.swing.JFrame {
- /**
- * Creates new form ExemploButtonRelatorio
- */
- public ExemploButtonRelatorio() {
- initComponents();
- }
- /**
- * This method is called from within the constructor to initialize the form.
- * WARNING: Do NOT modify this code. The content of this method is always
- * regenerated by the Form Editor.
- */
- @SuppressWarnings("unchecked")
- /**
- * @param args the command line arguments
- */
- public static void main(String args[]) {
- /* Create and display the form */
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- new ExemploButtonRelatorio().setVisible(true);
- }
- });
- }
- // Variables declaration - do not modify
- private relatorio.ButtonRelatorio buttonRelatorio1;
- // End of variables declaration
- }
=================================
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package controle;
- import java.sql.Connection;
- import java.util.HashMap;
- import net.sf.jasperreports.engine.JRException;
- import net.sf.jasperreports.engine.JasperFillManager;
- import net.sf.jasperreports.engine.JasperPrint;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class GeraRelatorio {
- private Connection con;
- public GeraRelatorio() throws Exception {
- this.con = new ConnectionFactoryComProperties().getConnection();
- }
- public JasperPrint gerarRelatorio(String arquivoJasper, HashMap map) throws JRException {
- JasperPrint rel = null;
- try {
- rel = JasperFillManager.fillReport(arquivoJasper, map, this.con);
- } catch (JRException e) {
- javax.swing.JOptionPane.showMessageDialog(null,e.getMessage(),"Mensagem",javax.swing.JOptionPane.ERROR_MESSAGE);
- }
- return rel;
- }
- }
Continuando agora com a sessão09BibliotecaDeClasses
Lembre-se de instalar os seguintes programas abaixo:
Iremos criar a seguinte interface:
Ao se clicar no botão Média Salários iremos visualizar o relatório gerado pelo software jasper ExemploGráfico.jasper:
Para isso devemos abrir o software Jasper:
Teremos a seguinte tela e precisaremos configurar a conexão com o BD postgre que já deve estar instalado na sua máquina:
No passo 2 iremos selecionar o tipo de gráfico que iremos criar:
Ao se clicar em next, next iremos utilizar a seguinte query:
Iremos selecionar todos os campos da tabela e iremos clicar no botão abaixo:
Iremos cair na seguinte tela que devemos selecionar o tipo de gráfico chart no canto direito da tela e arrastar para o centro:
Clicar com o botão direito em cima do gráfico e selecionar a opção Chart Data, iremos para a seguinte tela:
Clicar no botão report query e digitar o comando select abaixo:
Clicar em preview para visualizar como sairá o relatório:
PRONTO!!!
A partir de agora é só adicionar esse relatório ao evento click do botão
Com isso, iremos detalhar o código agora:
Começando pelo pacote visão, arquivo teste.java:
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package visao;
- /**
- *
- * @author paulo983
- */
- public class Teste extends javax.swing.JFrame {
- /**
- * Creates new form Teste
- */
- public Teste() {
- initComponents();
- }
- /**
- * This method is called from within the constructor to initialize the form.
- * WARNING: Do NOT modify this code. The content of this method is always
- * regenerated by the Form Editor.
- */
- private void buttonRelatorio2ActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- }
- /**
- * @param args the command line arguments
- */
- public static void main(String args[]) {
- /* Set the Nimbus look and feel */
- /* Create and display the form */
- java.awt.EventQueue.invokeLater(new Runnable() {
- public void run() {
- new Teste().setVisible(true);
- }
- });
- }
- // Variables declaration - do not modify
- private relatorio.ButtonRelatorio buttonRelatorio1;
- private relatorio.ButtonRelatorio buttonRelatorio2;
- private relatorio.ButtonRelatorio buttonRelatorio3;
- // End of variables declaration
- }
=================
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package relatorio;
- import controle.GeraRelatorio;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.Serializable;
- import java.util.HashMap;
- import javax.swing.JButton;
- import net.sf.jasperreports.engine.JasperPrint;
- import net.sf.jasperreports.view.JasperViewer;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class ButtonRelatorio extends JButton implements Serializable {
- private String nomeRelatorio;
- public ButtonRelatorio() {
- this.addActionListener(new ActionListener(){
- @Override
- public void actionPerformed(ActionEvent e){
- try {
- GeraRelatorio geraRelat = new GeraRelatorio();
- JasperPrint relatorio;
- HashMap map = new HashMap();
- map.put("SUBREPORT_DIR", "src/reports/"); // define a localização do sub-relatório
- relatorio = geraRelat.gerarRelatorio("src/reports/"+getNomeRelatorio(), map);
- JasperViewer.viewReport(relatorio, false);
- } catch (Exception ex) {
- javax.swing.JOptionPane.showMessageDialog(null, "Erro: " + ex.getMessage());
- }
- }
- });
- }
- public String getNomeRelatorio() {
- return nomeRelatorio;
- }
- public void setNomeRelatorio(String nomeRelatorio) {
- this.nomeRelatorio = nomeRelatorio;
- }
- }
- // Class InterfaceBean
- package interfacebeans;
- import java.awt.FlowLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.Serializable;
- import javax.swing.JButton;
- import javax.swing.JPanel;
- import javax.swing.JTextField;
- public class InterfaceBean extends JPanel implements Serializable{
- // atributos ativos
- private JTextField file;
- // atributos inativos
- private JButton mgs;
- private JButton fechar;
- public InterfaceBean(){
- setLayout(new FlowLayout());
- setSize(200, 300);
- file = new JTextField(10);
- file.setText("exemplo.txt");
- add(file);
- JButton msg = new JButton("Mensagem");
- msg.setMnemonic('M');
- msg.setToolTipText("Exibir Mensagem.");
- msg.addActionListener(
- new ActionListener(){
- @Override
- public void actionPerformed(ActionEvent e){
- javax.swing.JOptionPane.showMessageDialog(null,"Arquivo a ser lido: "+ file.getText() , "Mensagem", javax.swing.JOptionPane.INFORMATION_MESSAGE);
- }
- }
- );
- add(msg);
- fechar = new JButton("Fechar");
- fechar.setMnemonic('F');
- fechar.setToolTipText("Finaliza execução.");
- fechar.addActionListener(
- new ActionListener(){
- @Override
- public void actionPerformed(ActionEvent e){
- System.exit(0);
- }
- }
- );
- add(fechar);
- }
- public void setFileName(String f){
- file.setText(f);
- }
- public String getFileName(){
- return file.getText();
- }
- } // End of Class InterfaceBean
=============================
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package controle;
- import java.sql.Connection;
- import java.util.HashMap;
- import net.sf.jasperreports.engine.JRException;
- import net.sf.jasperreports.engine.JasperFillManager;
- import net.sf.jasperreports.engine.JasperPrint;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class GeraRelatorio {
- private Connection con;
- public GeraRelatorio() throws Exception {
- this.con = new ConnectionFactoryComProperties().getConnection();
- }
- public JasperPrint gerarRelatorio(String arquivoJasper, HashMap map) throws JRException {
- JasperPrint rel = null;
- try {
- rel = JasperFillManager.fillReport(arquivoJasper, map, this.con);
- } catch (JRException e) {
- javax.swing.JOptionPane.showMessageDialog(null,e.getMessage(),"Mensagem",javax.swing.JOptionPane.ERROR_MESSAGE);
- }
- return rel;
- }
- }
===============================
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package controle;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.Properties;
- /**
- *
- * @author Paulo Henrique Cayres
- */
- public class ConnectionFactoryComProperties{
- public Connection getConnection() {
- try {
- // Criação de um objeto de propriedades
- Properties prop = new Properties();
- // leitura/carga do arquivo texto com as propriedades
- prop.load( getClass().getResourceAsStream("../util/bancoDeDados.properties"));
- // obtenção do valor de cada parâmetro através do método getProperty
- String dbDriver = prop.getProperty("db.driver");
- String dbUrl = prop.getProperty("db.url");
- String dbUser = prop.getProperty("db.user");
- String dbPwd = prop.getProperty("db.pwd");
- Class.forName(dbDriver);
- return DriverManager.getConnection(dbUrl, dbUser, dbPwd);
- } catch (ClassNotFoundException | IOException | SQLException ex) {
- throw new RuntimeException(ex);
- }
- }
- }
======================================
Continuando agora com a sessão09Web
Iremos criar a seguinte tela, através de JSP e JavaBean:
Ao se clicar no botão enviar seremos redirecionado para a seguinte tela:
Para isso temos que criar o seguinte arquivo HTML:
- <!--
- To change this template, choose Tools | Templates
- and open the template in the editor.
- -->
- <!DOCTYPE html>
- <html>
- <head>
- <title>JSP e JavaBean</title>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
- </head>
- <body>
- <form method="post" action="ex01UseBean.jsp">
- Digite seu nome:
- <input type="text" name="nome" size="50" />
- <br />
- Selecione o sexo:
- <select name="sexo">
- <option value="Feminino">Feminino</option>
- <option value="Masculino">Masculino</option>
- </select>
- <br />
- <input type="reset" name="b1" value="Limpar" />
-   
- <input type="submit" name="b2" value="Enivar" />
- </form>
- </body>
- </html>
========================
- <%--
- Document : ex01UseBean
- Created on : 22/10/2013, 16:31:19
- Author : Paulo Henrique Cayres
- --%>
- <%@page contentType="text/html" pageEncoding="ISO-8859-1"%>
- <jsp:useBean id="pessoa" class="modelo.Pessoa" />
- <jsp:setProperty name="pessoa" property="nome" />
- <jsp:setProperty name="pessoa" property="sexo" />
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
- <title>JSP e JavaBean</title>
- </head>
- <body>
- <h1>Informações do objeto instanciado do Bean</h1>
- <hr>
- Nome: ${pessoa.nome}
- <br>
- Sexo: ${pessoa.sexo}
- <hr>
- <a href="ex01UseBean.html">Voltar</a>
- </body>
- </html>
==========================
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package modelo;
- public class Pessoa {
- private String nome;
- private String sexo;
- public Pessoa() {
- }
- public String getNome() {
- return nome;
- }
- public void setNome(String nome) {
- this.nome = nome;
- }
- public String getSexo() {
- return sexo;
- }
- public void setSexo(String sexo) {
- this.sexo = sexo;
- }
- }
=============================
Atividade 09
Atividade 09
Nesse exercício iremos montar uma página da seguinte forma:
ao clicar em enviar será mostrado uma mensagem:
Ao clicar em voltar poderemos listar o produto que foi armazenado em um ArrayList
O código da página para adicionar em um ArrayList é esse:
- <%--
- Document : exercicio1FormPedido.jsp
- Created on : 24/09/2013, 23:29:39
- --%>
- <%@page contentType="text/html" pageEncoding="ISO-8859-1"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
- <title>Exercicio01</title>
- </head>
- <body>
- <form action="exercicio1RespPedido.jsp" method="post">
- <table>
- <tr>
- <td>Descrição: </td><td> <input type="text" name="descricao"/></td>
- </tr>
- <tr>
- <td>Preço Unitario: </td><td> <input type="text" name="pcoUnitario"/></td>
- </tr>
- <tr>
- <td>Quantidade: </td><td> <input type="text" name="qtdade"/></td>
- </tr>
- </table>
- <input type="submit" value="Enviar"/>
- </form>
- <a href='exercicio1ListaProdutos.jsp'>Listar</a>
- </body>
- </html>
===========================
Ao clicar no botão enviar da tela acima será cadastrado no banco de dados conforme mostra a mensagem abaixo:
O código da página acima é esse:
- <%--
- Document : exercicio1RespPedido.jsp
- Created on : 24/09/2013, 23:29:39
- Author :
- --%>
- <%@page contentType="text/html" pageEncoding="ISO-8859-1"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
- <title>Exercicio01</title>
- </head>
- <body>
- <jsp:useBean id="prod1" class="modelo.Produto" scope="page">
- <jsp:setProperty name="prod1" property="*"/>
- </jsp:useBean>
- <jsp:useBean id="pedido1" class="modelo.Pedido" scope="session"/>
- <jsp:setProperty name="pedido1" property="novoProduto" value="${prod1}"/>
- <h1>Produto incluso com sucesso</h1>
- <a href="exercicio1FormPedido.jsp">Formulário de Pedido</a>
- </body>
- </html>
===================
Os produtos serão listados
O código da página acima é:
- <%--
- Document : exercicio1FormPedido
- Created on : 24/09/2013, 23:29:39
- Author :
- --%>
- <%@page contentType="text/html" pageEncoding="ISO-8859-1"%>
- <%@page import="modelo.Produto, java.util.ArrayList"%>
- <jsp:useBean id="pedido1" class="modelo.Pedido" scope="session"/>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
- <title>Exercicio01</title>
- </head>
- <body>
- <h1>LIsta de produtos cadastrados</h1><br />
- <table>
- <thead>
- <tr>
- <td>Descrição</td>
- <td>Preço Unitario</td>
- <td>Quantidade</td>
- </tr>
- </thead>
- <%
- ArrayList lista = pedido1.getLista();
- for (int x=0;x<lista.size();x++) {
- Produto prod = (Produto) lista.get(x);
- %>
- <tr>
- <td><%=prod.getDescricao()%></td>
- <td><%=prod.getPcoUnitario()%></td>
- <td><%=prod.getQtdade()%></td>
- </tr>
- <%}%>
- </table>
- </body>
- </html>
========================
O código da classe pedido é:
- package modelo;
- import modelo.Produto;
- import java.util.ArrayList;
- public class Pedido {
- ArrayList<Produto> lista = new ArrayList<Produto>();
- public void add(Produto p) {
- lista.add(p);
- }
- public ArrayList getLista() { return lista; }
- public void setNovoProduto(Produto p) {
- lista.add(p);
- }
- }
========================
O código da classe produto é:
- package modelo;
- public class Produto {
- private String descricao;
- private double pcoUnitario;
- private double qtdade;
- public String getDescricao() {
- return descricao;
- }
- public void setDescricao(String descricao) {
- this.descricao = descricao;
- }
- public double getPcoUnitario() {
- return pcoUnitario;
- }
- public void setPcoUnitario(double pcoUnitario) {
- this.pcoUnitario = pcoUnitario;
- }
- public double getQtdade() {
- return qtdade;
- }
- public void setQtdade(double qtdade) {
- this.qtdade = qtdade;
- }
- }
A estrutura de pastas está organizada dessa forma:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Capítulo 10:
Deployment de aplicação Java Web.
Primeiro passo: Instalação do Tomcat. Para fazer o download acesse: http://tomcat.apache.org. Caso seja utilizado o netbeans o ideal é já instalar o Tomcat junto com o netbeans. Para verificar se o Tomcat já está instalado vá em Ferramentas -> Servidores:
Caso já esteja instalado aparecerá o ícone do tomcat:
Com o Tomcat instalado acesse a página da seguinte forma localhost:8084. A seguinte tela será disponibilizada:
Para realizar o gerenciamento de aplicações web hospedadas pelo Tomcat, pode ser usada a aplicação Tomcat Web Application Manager:
==========================









































 
No comments:
Post a Comment