Oi, estou começando agora a aprender flex, e parei na parte de salvar com o banco na hora que vou incluir ele fecha a conexão, e não sei o que estou fazendo por falta de experiencia e tutorial do flex 4.5.. pois uso um jeito diferente do flex 3, para incluir... Se alguém tiver um tutorial que inclui no banco na versão do flex 4.5, ficaria grato tbm..
vou colocar aqui o meu código.. meu grande mais tomara que vocês me ajudam... é um cadastro simples! ClienteDTO ------------------------ package bean.dto; public class ClienteDTO { private int idCliente; private String nome; private String cpf; public int getIdCliente() { return idCliente; } public void setIdCliente(int idCliente) { this.idCliente = idCliente; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } } ConexaoDAO -------------------------- package bean.dao; import java.sql.*; public class ConexaoDAO { private static String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver"; private static String DATABASE_URL = "jdbc:oracle:thin:@127.0.0.1:1521:xe"; private static String login = "cliente"; private static String password = "cliente"; private static Connection conexao; public static Connection getConexao() { try { if (conexao == null) { Class.forName(JDBC_DRIVER); conexao = DriverManager.getConnection(DATABASE_URL, login, password); } return conexao; } catch (SQLException e) { e.printStackTrace(); System.exit(1); return null; } catch (ClassNotFoundException e) { e.printStackTrace(); System.exit(1); return null; } } public static void desconectar() { try { conexao.close(); } catch (SQLException e) { e.printStackTrace(); System.exit(1); } } } ClienteDAO ------------------------- package bean.dao; import bean.dto.ClienteDTO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import javax.swing.JOptionPane; public class ClienteDAO { public static String incluir(ClienteDTO clienteDTO) { Connection conexao = ConexaoDAO.getConexao(); String mensagem = ""; String sql = "insert into Cliente(idCliente,nome,cpf) values (?, ?, ?)"; try { PreparedStatement ps = conexao.prepareStatement(sql); ps.setInt(1, obterUltimoId() + 1); ps.setString(2, clienteDTO.getNome()); ps.setString(3, clienteDTO.getCpf()); ps.executeUpdate(); //ConexaoDAO.desconectar(); } catch (SQLException e) { // TODO Auto-generated catch block JOptionPane.showMessageDialog(null, "Erro na inserção da cliente no banco de dados"); //mensagem = "Erro na inserção da cliente no banco de dados"; //ConexaoDAO.desconectar(); e.printStackTrace(); } return mensagem; } public static String alterar(ClienteDTO clienteDTO) { Connection conexao = ConexaoDAO.getConexao(); String mensagem = ""; String sql = "Update Cliente " + "set nome = ?, " + "cpf = ? " + "where idCliente = ?"; try { PreparedStatement ps = conexao.prepareStatement(sql); ps.setString(1, clienteDTO.getNome()); ps.setString(2, clienteDTO.getCpf()); ps.setInt(3, clienteDTO.getIdCliente()); ps.executeUpdate(); //ConexaoDAO.desconectar(); } catch (SQLException e) { // TODO Auto-generated catch block mensagem = "Erro na alteração da cliente no banco de dados"; //ConexaoDAO.desconectar(); e.printStackTrace(); } return mensagem; } public static String excluir(ClienteDTO clienteDTO) { Connection conexao = ConexaoDAO.getConexao(); String mensagem = ""; String sql = "Delete from Cliente " + "where idCliente = ? "; try { PreparedStatement ps = conexao.prepareStatement(sql); ps.setInt(1, clienteDTO.getIdCliente()); ps.executeUpdate(); //ConexaoDAO.desconectar(); } catch (SQLException e) { // TODO Auto-generated catch block mensagem = "Erro na esclusão do objeto no banco de dados"; //ConexaoDAO.desconectar(); e.printStackTrace(); } return mensagem; } private static int obterUltimoId() { Connection conexao = ConexaoDAO.getConexao(); int ultimoId = 0; String sql = "select max(idCliente) ultimoId from Cliente"; try { PreparedStatement ps = conexao.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if (rs.next()) ultimoId = rs.getInt("ultimoId"); rs.getStatement().close(); //ConexaoDAO.desconectar(); } catch (SQLException e) { //ConexaoDAO.desconectar(); // TODO Auto-generated catch block e.printStackTrace(); } return ultimoId; } public static int obterQtde(ClienteDTO clienteDTO) { Connection conexao = ConexaoDAO.getConexao(); int qtde = 0; String sql = "select count(idCliente) qtde " + "from Cliente "; if (!clienteDTO.getNome().equals("")) sql = sql + "where nome = ? " + "and cpf = ?"; try { PreparedStatement ps = conexao.prepareStatement(sql); if (!clienteDTO.getNome().equals("")) { ps.setString(1, clienteDTO.getNome()); ps.setString(2, clienteDTO.getCpf()); } ResultSet rs = ps.executeQuery(); if (rs.next()) qtde = rs.getInt("qtde"); rs.getStatement().close(); //ConexaoDAO.desconectar(); } catch (SQLException e) { //ConexaoDAO.desconectar(); // TODO Auto-generated catch block e.printStackTrace(); } return qtde; } public static ClienteDTO obter(ClienteDTO clienteDTO) { Connection conexao = ConexaoDAO.getConexao(); String sql = "select * " + "from Cliente"; if (clienteDTO.getIdCliente() > 0) sql = sql + " where idCliente = ?"; else if (!clienteDTO.getNome().equals("")) sql = sql + " where nome = ? and cpf = ?"; try { PreparedStatement ps = conexao.prepareStatement(sql); int posicao = 1; if (clienteDTO.getIdCliente() > 0) ps.setInt(posicao,clienteDTO.getIdCliente()); else if (!clienteDTO.getNome().equals("")){ ps.setString(posicao,clienteDTO.getNome()); ps.setString(posicao+1,clienteDTO.getCpf()); } ResultSet rs = ps.executeQuery(); clienteDTO.setIdCliente(0); clienteDTO.setNome(""); clienteDTO.setCpf(""); if (rs.next()) { clienteDTO.setIdCliente(rs.getInt("idCliente")); clienteDTO.setNome(rs.getString("nome")); clienteDTO.setCpf(rs.getString("cpf")); } rs.getStatement().close(); //ConexaoDAO.desconectar(); return clienteDTO; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); clienteDTO.setIdCliente(0); clienteDTO.setNome(""); clienteDTO.setCpf(""); //ConexaoDAO.desconectar(); return clienteDTO; } } public static Vector<ClienteDTO> obterLista() { Connection conexao = ConexaoDAO.getConexao(); String sql = "Select * " + "from Cliente " + "order by Cliente.nome" ; //Select * from Cliente order by cliente.nome try { PreparedStatement ps = conexao.prepareStatement(sql); ResultSet rs = ps.executeQuery(); Vector clientes = new Vector(); if (rs.next()) { do { ClienteDTO clienteDTO = new ClienteDTO (); clienteDTO.setIdCliente(rs.getInt("idCliente")); clienteDTO.setNome(rs.getString("nome")); clienteDTO.setCpf(rs.getString("cpf")); clientes.add(clienteDTO); } while (rs.next()); } rs.getStatement().close(); //ConexaoDAO.desconectar(); return clientes; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); //ConexaoDAO.desconectar(); return null; } } } ClienteBusiness -------------------------------- package bean.business; import bean.dao.ClienteDAO; import bean.dto.ClienteDTO; import java.util.Vector; public class ClienteBusiness { public static String incluir(ClienteDTO clienteDTO) { String mensagem = validarInclusao(clienteDTO); if (mensagem.equals("")) mensagem = ClienteDAO.incluir(clienteDTO); return mensagem; } public static String alterar( ClienteDTO clienteDTONovo, ClienteDTO clienteDTOAntigo) { String mensagem = validarAlteracao(clienteDTONovo,clienteDTOAntigo); if (mensagem.equals("")) mensagem = ClienteDAO.alterar(clienteDTONovo); return mensagem; } public static String excluir(ClienteDTO clienteDTO) { ClienteDTO clienteDTOEncontrado = obter(clienteDTO); String mensagem = ""; if (clienteDTOEncontrado.getIdCliente() == 0) mensagem = "Cliente não encontrado " + "[id: " + clienteDTO.getIdCliente() + ", nome: " + clienteDTO.getNome()+"]"; else ClienteDAO.excluir(clienteDTO); return mensagem; } public static String validarInclusao(ClienteDTO clienteDTO) { // Validar se todos os atributos obrigatórios foram informados String mensagem = validarAtributo(clienteDTO); if (mensagem.equals("")) // Verificar se existe alguma cidade cadastrada com o mesmo nome // que está sendo incluído mensagem = validarChaveUnica(clienteDTO); return mensagem; } public static String validarAtributo(ClienteDTO clienteDTO) { String mensagem = ""; if (clienteDTO.equals(null)) mensagem = "Cliente sem conteúdo"; else if (clienteDTO.getNome().equals("")) mensagem = "Nome do Cliente não foi informado"; else if (clienteDTO.getCpf().equals("")) mensagem = "Cpf do Cliente não foi informado"; return mensagem; } public static String validarChaveUnica(ClienteDTO clienteDTO) { String mensagem = ""; ClienteDTO clienteDTOValidar = new ClienteDTO(); // Se o nome da cidade NÀO é "", verificar se já existe uma cidade cadastrada = o nome if (!clienteDTO.getNome().equals("")) { clienteDTOValidar.setNome(clienteDTO.getNome()); clienteDTOValidar.setCpf(clienteDTO.getCpf()); int qtde = ClienteDAO.obterQtde(clienteDTOValidar); if (qtde > 0 ) mensagem = "Já existe um cliente cadastrado com o nome " + clienteDTO.getNome(); } return mensagem; } public static String validarAlteracao(ClienteDTO clienteDTONovo, ClienteDTO clienteDTOAntigo) { // Validar se todos os atributos obrigatórios foram informados String mensagem = validarAtributo (clienteDTONovo); if (mensagem.equals("")) { // Verificar se a cidade antiga existe realmente no BD ClienteDTO clienteDTOEncontrado = new ClienteDTO(); clienteDTOEncontrado.setIdCliente(clienteDTOAntigo.getIdCliente()); clienteDTOEncontrado.setNome(""); clienteDTOEncontrado = obter(clienteDTOEncontrado); if (clienteDTOEncontrado.getIdCliente() == 0) mensagem = "cliente não encontrado " + "[ id: " + clienteDTOEncontrado.getIdCliente() + ", nome: " + clienteDTOEncontrado.getNome() +" ]"; // Verificar se já existe alguma cidade cadastrada com o mesmo nome da cidade que está sendo alterada // Somente fazer essa verificação se houve alteraçao no nome if ((! clienteDTONovo.getNome().equals(clienteDTOAntigo.getNome())) && (mensagem.equals(""))) { clienteDTOEncontrado.setNome(clienteDTONovo.getNome()); clienteDTOEncontrado.setNome(""); mensagem = validarChaveUnica (clienteDTOEncontrado); } } return mensagem; } public static void validarExclusao(){ } public static ClienteDTO obter(ClienteDTO clienteDTO) { clienteDTO = ClienteDAO.obter(clienteDTO); return clienteDTO; } public static Vector<?> obterLista() { Vector<?> clientes = new Vector(); clientes = ClienteDAO.obterLista(); return clientes; // retornar a lista de ClienteDTO } } web.xml -------------------------- <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>BlazeDS</display-name> <description>BlazeDS Application</description> <!-- Http Flex Session attribute and binding listener support --> <listener> <listener-class>flex.messaging.HttpFlexSession</listener- class> </listener> <!-- MessageBroker Servlet --> <servlet> <servlet-name>MessageBrokerServlet</servlet-name> <display-name>MessageBrokerServlet</display-name> <servlet-class>flex.messaging.MessageBrokerServlet</servlet- class> <init-param> <param-name>services.configuration.file</param-name> <param-value>/WEB-INF/flex/services-config.xml</param- value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- begin rdsend rds --> <servlet> <servlet-name>RDSDispatchServlet</servlet-name> <display-name>RDSDispatchServlet</display-name> <servlet-class>flex.rds.server.servlet.FrontEndServlet</ servlet-class> <init-param> <param-name>useAppserverSecurity</param-name> <param-value>false</param-value> </init-param> <load-on-startup>10</load-on-startup> </servlet> <servlet-mapping id="RDS_DISPATCH_MAPPING"> <servlet-name>RDSDispatchServlet</servlet-name> <url-pattern>/CFIDE/main/ide.cfm</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>MessageBrokerServlet</servlet-name> <url-pattern>/messagebroker/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> </welcome-file-list> <!-- for WebSphere deployment, please uncomment --> <!-- <resource-ref> <description>Flex Messaging WorkManager</description> <res-ref-name>wm/MessagingWorkManager</res-ref-name> <res-type>com.ibm.websphere.asynchbeans.WorkManager</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref> --> </web-app> service_config ------------------------------ <?xml version="1.0" encoding="UTF-8"?> <services-config> <services> <service-include file-path="remoting-config.xml" /> <service-include file-path="proxy-config.xml" /> <service-include file-path="messaging-config.xml" /> </services> <security> <login-command class="flex.messaging.security.TomcatLoginCommand" server="Tomcat"/> <!-- Uncomment the correct app server <login-command class="flex.messaging.security.TomcatLoginCommand" server="JBoss"> <login-command class="flex.messaging.security.JRunLoginCommand" server="JRun"/> <login-command class="flex.messaging.security.WeblogicLoginCommand" server="Weblogic"/ > <login-command class="flex.messaging.security.WebSphereLoginCommand" server="WebSphere"/> --> <!-- <security-constraint id="basic-read-access"> <auth-method>Basic</auth-method> <roles> <role>guests</role> <role>accountants</role> <role>employees</role> <role>managers</role> </roles> </security-constraint> --> </security> <channels> <channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel"> <endpoint url="http://{server.name}:{server.port}/ {context.root}/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/> </channel-definition> <channel-definition id="my-secure-amf" class="mx.messaging.channels.SecureAMFChannel"> <endpoint url="https://{server.name}:{server.port}/ {context.root}/messagebroker/amfsecure" class="flex.messaging.endpoints.SecureAMFEndpoint"/> <properties> <add-no-cache-headers>false</add-no-cache-headers> </properties> </channel-definition> <channel-definition id="my-polling-amf" class="mx.messaging.channels.AMFChannel"> <endpoint url="http://{server.name}:{server.port}/ {context.root}/messagebroker/amfpolling" class="flex.messaging.endpoints.AMFEndpoint"/> <properties> <polling-enabled>true</polling-enabled> <polling-interval-seconds>4</polling-interval-seconds> </properties> </channel-definition> <!-- <channel-definition id="my-http" class="mx.messaging.channels.HTTPChannel"> <endpoint url="http://{server.name}:{server.port}/ {context.root}/messagebroker/http" class="flex.messaging.endpoints.HTTPEndpoint"/> </channel-definition> <channel-definition id="my-secure-http" class="mx.messaging.channels.SecureHTTPChannel"> <endpoint url="https://{server.name}:{server.port}/ {context.root}/messagebroker/httpsecure" class="flex.messaging.endpoints.SecureHTTPEndpoint"/> <properties> <add-no-cache-headers>false</add-no-cache-headers> </properties> </channel-definition> --> </channels> <logging> <target class="flex.messaging.log.ConsoleTarget" level="Error"> <properties> <prefix>[BlazeDS] </prefix> <includeDate>false</includeDate> <includeTime>false</includeTime> <includeLevel>false</includeLevel> <includeCategory>false</includeCategory> </properties> <filters> <pattern>Endpoint.*</pattern> <pattern>Service.*</pattern> <pattern>Configuration</pattern> </filters> </target> </logging> <system> <redeploy> <enabled>false</enabled> <!-- <watch-interval>20</watch-interval> <watch-file>{context.root}/WEB-INF/flex/services- config.xml</watch-file> <watch-file>{context.root}/WEB-INF/flex/proxy-config.xml</ watch-file> <watch-file>{context.root}/WEB-INF/flex/remoting- config.xml</watch-file> <watch-file>{context.root}/WEB-INF/flex/messaging- config.xml</watch-file> <watch-file>{context.root}/WEB-INF/flex/data-management- config.xml</watch-file> <touch-file>{context.root}/WEB-INF/web.xml</touch-file> --> </redeploy> </system> </services-config> Remoting --------------------- <?xml version="1.0" encoding="UTF-8"?> <service id="remoting-service" class="flex.messaging.services.RemotingService"> <adapters> <adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/> </adapters> <default-channels> <channel ref="my-amf"/> </default-channels> <destination id="ClienteService"> <properties> <source>bean.business.ClienteBusiness</source> </properties> </destination> </service> Agora o flex -------------------------- Pagina inicial --------------------------- <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" backgroundColor="#E5FBDC"> <fx:Declarations> </fx:Declarations> <fx:Script> <![CDATA[ import mx.controls.Alert; import mx.events.FlexEvent; import mx.managers.PopUpManager; import spark.components.TitleWindow; private function showListaCliente():void { var cliente:TWListaClientes = TWListaClientes(PopUpManager.createPopUp(this, TWListaClientes, true)); PopUpManager.centerPopUp(cliente); } ]]> </fx:Script> <s:Button x="10" y="10" label="Gerenciamento de Clientes" click="showListaCliente()"/> </s:Application> ------------------------------- Um componente TitleWindow que cadastra -------------------------- <?xml version="1.0" encoding="utf-8"?> <s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:services="services.*" xmlns:valueObjects="valueObjects.*" width="500" height="226" close="PopUpManager.removePopUp(this)" enabled="true" title="Cadastro de Clientes"> <fx:Script> <![CDATA[ import mx.controls.Alert; import mx.managers.PopUpManager; import valueObjects.ClienteDTO; protected function salvar_clickHandler(event:MouseEvent):void { var clienteDTO:ClienteDTO = new ClienteDTO(); clienteDTO.nome = nomeCliente.text; clienteDTO.cpf = cpfCliente.text; incluirResult.token = clienteService.incluir(clienteDTO); } ]]> </fx:Script> <fx:Declarations> <s:CallResponder id="incluirResult"/> <services:ClienteService id="clienteService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/> <valueObjects:ClienteDTO id="clienteDTO"/> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <s:Form x="0" y="0" width="100%" height="163"> <s:FormItem width="127" label="Código:"> <s:TextInput width="40" id="idCliente"/> </s:FormItem> <s:FormItem width="477" label="Nome:"> <s:TextInput width="410" id="nomeCliente"/> </s:FormItem> <s:FormItem width="324" label="CPF:"> <s:TextInput id="cpfCliente" width="184"/> </s:FormItem> </s:Form> <s:HGroup x="10" y="167" width="487" height="28"> <s:Button id="salvar" label="Salvar" click="salvar_clickHandler(event)"/> <s:Button label="Cancelar" id="cancelar"/> <s:Button label="Sair" id="sair"/> </s:HGroup> </s:TitleWindow> ---------------------------- Um componente TitleWindow que lista --------------------------------- <?xml version="1.0" encoding="utf-8"?> <s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" width="568" height="298" close="PopUpManager.removePopUp(this)" enabled="true" title="Gerenciamento de Clientes"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <fx:Script> <![CDATA[ import mx.managers.PopUpManager; import spark.components.TitleWindow; private function showCadastroCliente():void { var cliente:TWCadastroCliente = TWCadastroCliente(PopUpManager.createPopUp(this, TWCadastroCliente, true)); PopUpManager.centerPopUp(cliente); } ]]> </fx:Script> <s:HGroup x="54" y="10" width="462" height="33"> <s:Button height="23" label="Buscar"/> <s:ComboBox width="157"/> <s:TextInput width="215" height="23"/> </s:HGroup> <s:DataGrid x="21" y="47" width="524" height="181" requestedRowCount="4"> <s:columns> <s:ArrayList> <s:GridColumn dataField="dataField1" headerText="Código"></ s:GridColumn> <s:GridColumn dataField="dataField2" headerText="Nome do Cliente"></s:GridColumn> <s:GridColumn dataField="dataField3" headerText="CPF"></ s:GridColumn> <s:GridColumn dataField="" headerText="" width="30" sortable="false"> <s:itemRenderer> <fx:Component> <s:GridItemRenderer> <mx:VBox horizontalAlign="center" buttonMode="true"> <s:Image source="\images\edit.png" buttonMode="true"/> </mx:VBox> </s:GridItemRenderer> </fx:Component> </s:itemRenderer> </s:GridColumn> <s:GridColumn dataField="" headerText="" width="30" sortable="false"> <s:itemRenderer> <fx:Component> <s:GridItemRenderer> <mx:VBox horizontalAlign="center" buttonMode="true"> <s:Image source="\images\deletar.png" buttonMode="true"/> </mx:VBox> </s:GridItemRenderer> </fx:Component> </s:itemRenderer> </s:GridColumn> </s:ArrayList> </s:columns> <s:typicalItem> <fx:Object dataField1="Sample Data" dataField2="Sample Data" dataField3="Sample Data"></fx:Object> </s:typicalItem> <s:ArrayList> <fx:Object dataField1="data1" dataField2="data1" dataField3="data1"></fx:Object> <fx:Object dataField1="data2" dataField2="data2" dataField3="data2"></fx:Object> <fx:Object dataField1="data3" dataField2="data3" dataField3="data3"></fx:Object> <fx:Object dataField1="data4" dataField2="data4" dataField3="data4"></fx:Object> </s:ArrayList> </s:DataGrid> <s:HGroup x="10" width="100%" height="27" verticalCenter="119"> <s:Button label="Inserir" click="showCadastroCliente()"/> </s:HGroup> </s:TitleWindow> ----------------- é isso preciso de um ajuda urgente... estou precisando de uma luz... -- Você recebeu esta mensagem porque está inscrito na lista "flexdev" Para enviar uma mensagem, envie um e-mail para flexdev@googlegroups.com Para sair da lista, envie um email em branco para flexdev-unsubscr...@googlegroups.com Mais opções estão disponíveis em http://groups.google.com/group/flexdev