Galera estou com mais um dúvida!!!
Estou usando Struts, como eu posso fazer para gravar, alterar, excluir e localizar tudo em um só formulário?
Alguém pode me ajudar?
Galera estou com mais um dúvida!!!
Estou usando Struts, como eu posso fazer para gravar, alterar, excluir e localizar tudo em um só formulário?
Alguém pode me ajudar?
Cara esse artigo é o que eu mais leio, hehehee
Mais é uma action para cada ação, teria como fazer tudo em uma action só?
você acha melhor fazer tudo separado?
mas da mais serviço!!!
Só existe estas duas formas?
Agora sim você me entendeu, hehehe, valeu cara vou fazer aqui depois coloco a solução pro pessoal
cara fui testar o seu exemplo mais nao funcionou poderia ser mais objetivo!!!
meu jsp e esse
<%@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”/>
html:base/
<html:form action=“clienteaction” focus=“nome”>
<html:hidden property=“acao” />
<bean:message key=“data_cadastro”/> |
<html:text property=“data_cadastro” size=“30” /> |
e essa é minha classe persistencia
package clientes.persistencia;
import clientes.bean.Cliente;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.activation.DataSource;
import service.ServicePool;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
/**
*
@author Diogo
*/
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 ArrayList listarCliente(Cliente cliente) throws SQLException{
try {
con = ServicePool.getConexao(JNDINome);
}catch (Exception e){
e.printStackTrace();
}
String sql = "SELECT * FROM clientes WHERE nome = ?";
ArrayList resultado = new ArrayList();
try{
stmt = con.prepareStatement(sql);
stmt.setObject(1, cliente.getData_cadastro());
stmt.setObject(2, cliente.getData_nascimento());
stmt.setObject(3, cliente.getEndereco());
stmt.setObject(4, cliente.getBairro());
stmt.setObject(5, cliente.getCep());
stmt.setObject(6, cliente.getCidade());
stmt.setObject(7, cliente.getEstado());
stmt.setObject(8, cliente.getFone1());
stmt.setObject(9, cliente.getFone2());
stmt.setObject(10, cliente.getFone3());
stmt.setObject(11, cliente.getCnpj());
stmt.setObject(12, cliente.getIe());
stmt.setObject(13, cliente.getEmail());
stmt.setObject(14, cliente.getNome());
resultado.add(cliente);
}
catch (SQLException e) {
throw e;
}
finally {
desconecta();
}
return resultado;
}
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, cliente.getData_nascimento());
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();
}
}
public void alterarCliente(Cliente cliente) throws SQLException{
try {
con = ServicePool.getConexao(JNDINome);
} catch (Exception e) {
e.printStackTrace();
}
String sql = “UPDATE clientes set data_cadastro = ? ,data_nascimento = ? ,” +
“endereco = ?,bairro = ?,cep = ? ,cidade = ?,” +
“estado = ?,fone1 = ? ,fone2 = ?,fone3 = ?,cnpj = ? ,ie = ?,email = ? WHERE nome = ?”;
try{
stmt = con.prepareStatement(sql);
stmt.setObject(1, cliente.getData_cadastro());
stmt.setObject(2, cliente.getData_nascimento());
stmt.setObject(3, cliente.getEndereco());
stmt.setObject(4, cliente.getBairro());
stmt.setObject(5, cliente.getCep());
stmt.setObject(6, cliente.getCidade());
stmt.setObject(7, cliente.getEstado());
stmt.setObject(8, cliente.getFone1());
stmt.setObject(9, cliente.getFone2());
stmt.setObject(10, cliente.getFone3());
stmt.setObject(11, cliente.getCnpj());
stmt.setObject(12, cliente.getIe());
stmt.setObject(13, cliente.getEmail());
stmt.setObject(14, cliente.getNome());
stmt.executeUpdate();
}
catch (SQLException e) {
throw e;
}
finally {
desconecta();
}
}
public void excluiCliente(String nome) throws SQLException{
try {
con = ServicePool.getConexao(JNDINome);
} catch (Exception e) {
e.printStackTrace();
}
String sql = “DELETE FROM clientes WHERE nome = ?”;
try{
stmt = con.prepareStatement(sql);
stmt.setObject(1, nome);
stmt.executeUpdate();
}
catch (SQLException e) {
throw e;
}
finally {
desconecta();
}
}
}
ola nao sei se entendi… faço algo em struts… tem a entidade que gera tabela no banco de dados pois é em hibernate, tem o form… que é parecido com a entidade, só a declaração de variaveis, getters e setters… e também o action… no action vai todos os métodos… de alterar, etc…
só que geralmente o listar eu faço separado… aí vai os links para alterar e excluir após cada lista…
uma página cadastra, outra lista… acho que é a melhor forma… vc quer tuda na mesma… também estou precisando disto… e preciso por na sessão, pois quero pegar dados de duas tabelas e juntar em outras… monto um projeto que simula uma loja de carros, quero juntar clientes e carros, com vendas… ja fiz utilizando pesquisa por id, que da um retorno… mas preciso uma pesquisa por nome… e podem vir muitos retornos… entao empaquei… nisto aqui…
no action vc faz um if para cada op (operação )
if (op.equals("excluir)) {
retorno= metododeexcluir(mapping,form,request,response)
no jsp está assim… copiei agora…
ele captura o id do cliente no caso… la tem que fazer uma pesquisa talvez…
nao sei se ajudo ?
Lista de Clientes | |||||||||||
id | nome | rua | complemento | cidade | estado | cep | fone | rg | cpf | manutencao | |
${cliente.cidade.cidade} | ${cliente.estado.estado} | ">excluir-|- ">alterar |
Galera desde ja agradeço novamente a ajuda de vcs, mas acho que não estou me expressando bem!!!
Eu quero fazer uma consulta no banco pelo nome e que ao me retornar os valores lance no mesmo form que uso para cadastrar, agora sim acho que vcs irão me ajudar, valeu galera
Acredito q sei o q vc qr dizer.
Vou por um exemplo abaixo e daí vc pode ver se está correto o q eu interpretei.
Mas para começar, vc já ouviu falar em DispatchAction?
Bom, ela permite q vc faça um switch entre os ActionForwards.
Assim cm vc tbm pode usar um única jsp para poder fazer o tratamento de delete, insert e update.
Segue os códigos exemplos:
JSP alunos:
<%@ taglib uri="/WEB-INF/taglib/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/taglib/struts-bean.tld" prefix="bean" %>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>[Sistema de Projeto Final]</title>
</head>
<body>
</center>
<table>
<tr><td>
<input value="Cadastra" class="buttom" name="saveAluno"
onclick="window.location='<%=request.getContextPath()%>/Aluno.do?method=view&page=cadastro'"
style="border: 1px solid #747373; width:160px;
background-color:#D0FFD0; text-align: center;">
</td></tr>
<tr><td>
<input value="Remove" class="buttom" name="removeAluno"
onclick="window.location='<%=request.getContextPath()%>/Aluno.do?method=view&page=remove'"
style="border: 1px solid #747373; width:160px;
background-color:#D0FFD0; text-align: center;">
</td></tr>
<tr><td>
<input value="Atualiza" class="buttom" name="viewAluno"
onclick="window.location='<%=request.getContextPath()%>/Aluno.do?method=view&page=atualiza'"
style="border: 1px solid #747373; width:160px;
background-color:#D0FFD0; text-align: center;">
</td></tr>
<tr><td>
<input value="Voltar" class="buttom" name="voltar"
onclick="window.location='<%=request.getContextPath()%>/portal/menu.jsp'"
style="border: 1px solid #747373; width:160px;
background-color:#D0FFD0; text-align: center;">
</td></tr>
</table>
</center>
</body>
JSP acoesAluno:
<%@ taglib uri="/WEB-INF/taglib/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/taglib/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/taglib/c.tld" prefix="c" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>[Sistema de Projeto Final]</title>
<script language="JavaScript"
src="<%=request.getContextPath()%>/js/functions.js"
type="text/javascript">
</script>
</head>
<body style="width:50%; height:60%;">
<html:form action="Aluno.do">
<input name="method" value="" type="hidden">
<c:if test="${(page == 'cadastro') || (page == 'altera')}">
<table align="center" cellspacing="4">
<tr><td colspan="2">
<c:if test="${page == 'cadastro'}">
<bean:message key="cadastro1"/>
<bean:message key="aluno"/>
<bean:message key="cadastro2"/>
</c:if>
<c:if test="${page == 'altera'}">
<bean:message key="altera"/>
</c:if>
</td></tr>
<tr>
<td>
<bean:message key="nome"/>
</td>
<td>
<html:text property="nome"/>
</td>
</tr>
<br>
<tr>
<td>
<bean:message key="login"/>
</td>
<td>
<html:text property="login"/>
</td>
</tr>
<br>
<tr>
<td>
<bean:message key="senha"/>
</td>
<td>
<html:text property="senha"/>
</td>
</tr>
<br>
<tr>
<td>
<bean:message key="confirmarSenha"/>
</td>
<td>
<html:text property="confirmarSenha"/>
</td>
</tr>
<br>
<tr>
<td>
<bean:message key="mail"/>
</td>
<td>
<html:text property="mail"/>
</td>
</tr>
<br>
<tr>
<td>
<bean:message key="aluno.numMatricula"/>
</td>
<td>
<c:if test="${page == 'cadastro'}">
<html:text property="matricula"/>
</c:if>
<c:if test="${page == 'altera'}">
<html:hidden property="matricula"/>
<c:out value="${aluno.matricula}"/>
</c:if>
</td>
</tr>
<br>
</table>
</c:if>
<c:if test="${(page == 'remove') || (page == 'atualiza')}">
<table align="center" cellspacing="4">
<tr><td colspan="2">
<bean:message key="texto1"/>
<bean:message key="login"/>
<bean:message key="texto2"/>
<bean:message key="aluno"/>
<bean:message key="texto3"/>
<c:if test="${page == 'remove'}">
<bean:message key="remover"/>
</c:if>
<c:if test="${page == 'atualiza'}">
<bean:message key="atualizar"/>
</c:if>
</td></tr>
<tr>
<td>
<bean:message key="login"/>
</td>
<td>
<html:text property="login"/>
</td>
</tr>
<br>
</table>
</c:if>
<table align="center">
<tr>
<td>
<c:if test="${(page == 'cadastro') || (page == 'altera')}">
<input type="submit" name="saveAluno" value="Salvar"
class="buttom" onClick="javascript:setMethod('saveAluno')"
style="border: 1px solid #747373; width:160px;
background-color:#D0FFD0;">
</c:if>
<c:if test="${page == 'remove'}">
<input type="submit" name="removeAluno" value="Remover"
class="buttom" onClick="javascript:setMethod('removeAluno')"
style="border: 1px solid #747373; width:160px;
background-color:#D0FFD0;">
</c:if>
<c:if test="${page == 'atualiza'}">
<input type="submit" name="viewAluno" value="Busca"
class="buttom" onClick="javascript:setMethod('viewAluno')"
style="border: 1px solid #747373; width:160px;
background-color:#D0FFD0;">
</c:if>
</td>
<td>
<input value="Voltar" class="buttom" name="voltar"
onclick="window.location='<%=request.getContextPath()%>/portal/alunos.jsp'"
style="border: 1px solid #747373; width:160px;
background-color:#D0FFD0; text-align: center;">
</td>
</tr>
</table>
</html:form>
</body>
</html>
ACTION AlunoAction:
package web.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import persistencia.Singleton;
import web.form.AlunoForm;
import beans.Aluno;
public class AlunoAction extends DispatchAction{
private Singleton singleton = Singleton.getInstance();
public ActionForward saveAluno(ActionMapping mapping,
ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception {
AlunoForm alunoForm = (AlunoForm) form;
Aluno aluno = new Aluno();
boolean sucesso;
long matricula = -1;
if (!GenericValidator.isBlankOrNull(alunoForm.getMatricula())) {
aluno = this.singleton.containAluno(Long.parseLong(alunoForm.getMatricula()));
if (aluno == null)
aluno = new Aluno();
else
matricula = Long.parseLong(alunoForm.getMatricula());
}
aluno.setNome(alunoForm.getNome());
aluno.setLogin(alunoForm.getLogin());
aluno.setSenha(alunoForm.getSenha());
aluno.setMatricula(Integer.parseInt(alunoForm.getMatricula()));
aluno.setMail(alunoForm.getMail());
if (matricula == -1)
sucesso = this.singleton.addAluno(aluno);
else{
Aluno alunoAntigo = this.singleton.containAluno(matricula);
this.singleton.update(alunoAntigo, aluno);
sucesso = true;
}
if (sucesso)
return mapping.findForward("sucesso");
else
return mapping.findForward("falha");
}
public ActionForward removeAluno(ActionMapping mapping,
ActionForm form,HttpServletRequest request,
HttpServletResponse response) throws Exception {
AlunoForm alunoForm = (AlunoForm) form;
boolean sucesso = this.singleton.removeAluno(alunoForm.getLogin());
if (sucesso)
return mapping.findForward("sucesso");
else
return mapping.findForward("falha");
}
public ActionForward viewAluno(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
AlunoForm alunoForm = (AlunoForm) form;
String login = (alunoForm.getLogin());
Aluno aluno = this.singleton.containAluno(login);
if (aluno == null)
return mapping.findForward("falha");
alunoForm.setNome(aluno.getNome());
alunoForm.setSenha(aluno.getSenha());
alunoForm.setConfirmarSenha(aluno.getSenha());
alunoForm.setMatricula(""+aluno.getMatricula());
alunoForm.setMail(aluno.getMail());
String page = new String("altera");
request.setAttribute("page", page);
request.setAttribute("aluno", aluno);
return mapping.findForward("acoesAluno");
}
public ActionForward view(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
String page = request.getParameter("page");
request.setAttribute("page", page);
return mapping.findForward("acoesAluno");
}
}
STRUTS struts-config.xml
<struts-config>
<data-sources>
</data-sources>
<form-beans>
<form-bean
name="alunoForm"
type="web.form.AlunoForm"/>
</form-beans>
<global-exceptions>
</global-exceptions>
<global-forwards>
<forward
name="sucesso"
path="/portal/sucesso.jsp"/>
<forward
name="falha"
path="/portal/falha.jsp"/>
<forward
name="index"
path="/portal/menu.jsp"/>
</global-forwards>
<action-mappings>
<action
path="/Aluno"
type="web.action.AlunoAction"
parameter="method"
name="alunoForm"
scope="request"
validate="true">
<forward
name="acoesAluno"
path="/portal/acoesAluno.jsp"/>
</action>
</action-mappings>
<message-resources parameter="MessageResources"/>
</struts-config>
Bom, dessa forma vc consegue fazer os 3 passos em 1 jsp, 1 action e 1 formulário.
Espero ter ajudado.
Att,
Muito obrigado por ter me ajudado vou dar uma olhada no codigo e tentar fazer parecido, quando conseguir vou colocar a solução aqui para o pessoal dar uma olhada, valeu mesmo
Teria sim, mas não aconselho.
pegando o parametro passado no struts-config.xml
chamado parameter
<action
path="/logar"
name="efetuarLoginForm"
scope="session"
parameter="acao"
type="br.com.action.EfetuarLoginAction">
<forward name="sucesso" path="/index.jsp"/>
</action>
Agora que eu entendi o que vc ker.
Faz assim:
no struts-config.xml
<action
path="/logar"
name="efetuarLoginForm"
scope="session"
parameter="acao"
type="br.com.action.EfetuarLoginAction">
<forward name="sucesso" path="/index.jsp"/>
lt;/action>
JSP
<h:form method="post" action="manterUsuario.do">
<h:hidden property="acao" />
<input style="cursor: pointer" class="botao" type="button" value="Confirmar" onclick="javascript:executar('pesquisar')" />
</h:form>
javascript
formulario.acao.value = opcao;
formulario.submit();
o link ficaria assim
http://localhost:8080/MyProjeto/manterUsuario.do?acao=pesquisar