Botão Salvar com ações gravar e alterar

8 respostas
diogoprosoft

Galera estou usando STRUTS e estou com dificuldade de criar um botão salvar que tenha a função de gravar se não existir registro no banco ou alterar se já existir, ouvi falar que posso usar transação mas não sei como usar alguém pode me ajudar?

8 Respostas

J

geralmente eu enviu um variavel para a pagina que cadastra

cadastro.jsp?codigoAluno=1

cria um string nomeBotao

if(cofigoAluno==1) {

nomeBotao"Alterar";

}else{

nomeBotao=Cadastrar”

}

ai coloca essa variavel dentro do submit

diogoprosoft

cara desde já quero te agradecer por responder minha pergunta, mais você poderia se expressar melhor, como eu posso fazer isso?

J

ex.:

vc tem uma página Listagem
dentro dessa página vc tem a opcao: cadastrar / alterar / excluir

na página jsp onde vc faz o cadastro vc coloca uma variavel para testa exe.: envia o codigo do cliente para sua jsp se existir vc manda alterar se naum vc manda cadastrar.

diogoprosoft

valeu cara vou testar aqui, obrigado até a próxima

diogoprosoft

Esta e uma parte da minha classe persistencia, tenho que mudar algum código aqui?

public class Persistencia {

private static final String JNDINome = "jdbc/sicewebbd";

Connection con = null;
ResultSet rs = null;
PreparedStatement stmt = null;

   
public void desconecta(){
    if (rs != null){
        try{
            rs.close();
        }catch(SQLException e){
            
        }
    }
    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException e) {
       }
     }
   if (con != null) {
        try {
            con.close();
        } catch (SQLException e) {
      }
    }
}

public void insertCliente(Cliente cliente) throws SQLException{

    try {
        con = ServicePool.getConexao(JNDINome);
    } catch (Exception e) {
        e.printStackTrace();
    }
    String sql = "INSERT INTO clientes (data_cadastro,nome,data_nascimento,endereco,bairro,cep,cidade," +
                      "estado,fone1,fone2,fone3,cnpj,ie,email) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    
    try{            
        stmt = con.prepareStatement(sql);            
        stmt.setObject(1, cliente.getData_cadastro());
        stmt.setObject(2, cliente.getNome());
        stmt.setObject(3, new Date(cliente.getData_nascimento().getTime()));
        stmt.setObject(4, cliente.getEndereco());
        stmt.setObject(5, cliente.getBairro());
        stmt.setObject(6, cliente.getCep());
        stmt.setObject(7, cliente.getCidade());
        stmt.setObject(8, cliente.getEstado());
        stmt.setObject(9, cliente.getFone1());
        stmt.setObject(10, cliente.getFone2());
        stmt.setObject(11, cliente.getFone3());
        stmt.setObject(12, cliente.getCnpj());
        stmt.setObject(13, cliente.getIe());
        stmt.setObject(14, cliente.getEmail());
                   
        stmt.executeUpdate();
                
    }
    catch (SQLException e) {
        throw e;            
    }
    finally {                     
        desconecta();
    }                  
}

}

J

vc precisa criar uma metodo agora cara alterar
e na sua jsp onde cadastrar
vc faz a validação para ve se vai jogar para cadastrar ou alterar

diogoprosoft

ok vou criar agora.

diogoprosoft

aqui está minha metódo alterar

public void alterarCliente(Cliente cliente) throws SQLException{

try {

con = ServicePool.getConexao(JNDINome);

} catch (Exception e) {

e.printStackTrace();

}

String sql = “UPDATE clientes set data_cadastro = ? ,nome = ? ,data_nascimento = ? ,” +

“endereco = ?,bairro = ?,cep = ? ,cidade = ?,” +

“estado = ?,fone1 = ? ,fone2 = ?,fone3 = ?,cnpj = ? ,ie = ?,email = ?”;
try{            
        stmt = con.prepareStatement(sql);            
        stmt.setObject(1, cliente.getData_cadastro());
        stmt.setObject(2, cliente.getNome());
        stmt.setObject(3, new Date(cliente.getData_nascimento().getTime()));
        stmt.setObject(4, cliente.getEndereco());
        stmt.setObject(5, cliente.getBairro());
        stmt.setObject(6, cliente.getCep());
        stmt.setObject(7, cliente.getCidade());
        stmt.setObject(8, cliente.getEstado());
        stmt.setObject(9, cliente.getFone1());
        stmt.setObject(10, cliente.getFone2());
        stmt.setObject(11, cliente.getFone3());
        stmt.setObject(12, cliente.getCnpj());
        stmt.setObject(13, cliente.getIe());
        stmt.setObject(14, cliente.getEmail());
                   
        stmt.executeUpdate();
                
    }
    catch (SQLException e) {
        throw e;            
    }
    finally {                     
        desconecta();
    }

}

==========================================================

e aqui está meu jsp

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

<%@ taglib uri=“http://struts.apache.org/tags-logic” prefix=“logic” %>
<%@ taglib uri=“http://struts.apache.org/tags-html” prefix=“html” %>
<%@ taglib uri=“http://struts.apache.org/tags-bean” prefix=“bean” %>

<html:html locale=“true”>



<bean:message key=“css”/>

<bean:message key=“titulo”/>

<a>html:base/</a>





<html:form action=“clienteaction” focus=“nome”>




<tr>
                <td><bean:message key="nome"/></td>
                <td><label>
                    <html:text property="nome" size="50" /><html:errors property="nome"/>
                 </label></td>
            </tr>

            <tr>
                <td><bean:message key="data_nascimento"/></td>
                <td><label>
                    <html:text property="data_nascimento" size="30" />
                 </label></td>
            </tr>   
            
            <tr>
                <td><bean:message key="endereco"/></td>
                 <td><label>
                    <html:text property="endereco" size="50" /><html:errors property="endereco"/>
                </label></td>
             </tr>

            <tr>
                 <td><bean:message key="bairro"/></td>
                <td><label>
                    <html:text property="bairro" /><html:errors property="bairro"/>
                 </label></td>
            </tr>
            
            <tr>
                <td><bean:message key="cep"/></td>
                <td><label>
                    <html:text property="cep" size="30" />
                </label></td>
            </tr>

            <tr>
                <td><bean:message key="cidade"/></td>
                <td><label>
                    <html:text property="cidade" size="30" /><html:errors property="cidade"/>
                </label></td>
            </tr>
            
            <tr>
                <td><bean:message key="estado"/></td>
                <td><label>
                    <html:text property="estado" size="5" />
                  </label></td>
            </tr>

            <tr>
                <td><bean:message key="fone1"/></td>
                <td><label>
                    <html:text property="fone1" size="30" /><html:errors property="fone1"/>
                </label></td>
            </tr>
    
            <tr>
                <td><bean:message key="fone2"/></td>
                <td><label>
                    <html:text property="fone2" size="30" />
                </label></td>
            </tr>
            
            <tr>
                <td><bean:message key="fone3"/></td>
                <td><label>
                    <html:text property="fone3" size="30" />
                  </label></td>
            </tr>

            <tr>
                <td><bean:message key="cnpj"/></td>
                <td><label>
                    <html:text property="cnpj" size="30" />
                </label></td>
            </tr>

            <tr>
                <td><bean:message key="ie"/></td>
                <td><label>
                    <html:text property="ie" size="30" />
                </label></td>
            </tr>

            <tr>
                <td><bean:message key="email"/></td>
                <td><label>
                    <html:text property="email" size="50" />
                     </label></td>
            </tr>

            <tr>
                <td><label>
                        <html:submit><bean:message key="gravar"/></html:submit>                           
                </label></td>
            </tr>
     </table>
    </html:form>
</body>

</html:html>

O que devo fazer agora para finalizar?

<bean:message key=“data_cadastro”/>
<html:text property=“data_cadastro” size=“30” />
Criado 19 de maio de 2008
Ultima resposta 19 de mai. de 2008
Respostas 8
Participantes 2