Problema Struts DispatchAction

1 resposta
lgi2020

Bom dia, amigos.

Estou aprendendo a usar o Struts (1.3.8) e estou com uma dúvida na seguinte situação:

  • estou desenvolvendo uma aplicação simples para gerenciamento de contatos;

  • possuo as seguintes classes na minha aplicação:

    • Contato (um bean);
    • ContatoDao (interação com o BD com métodos para listar, remover…);
    • ContatoAction (uma action com os métodos ‘listar’, ‘remover’, ‘adicionar’ e ‘editar’;
    • ContatoForm (um ActionForm, implementa o método validate());
  • se, no arquivo struts-config.xml, minha action estiver setada para validate=“true”, não consigo utilizar a dispatchaction para somente listar ou remover (métodos que não precisam passar pelo formulário).

Se houver alguém que possa analisar o código e me dizer o que está havendo (se está certo ou errado) e ainda puder fazer comentários sugestões sobre o código, ficarei muito agradecido.

Abaixo, seguem os fontes do projeto.

Abraços a todos.

//ContatoAction.java
package br.com.exemplo.controller.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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 br.com.exemplo.controller.form.ContatoForm;
import br.com.exemplo.model.bean.Contato;
import br.com.exemplo.model.dao.ContatoDao;

public class ContatoAction extends DispatchAction
{
	public ActionForward adicionar(ActionMapping map, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		ContatoDao contatoDao = new ContatoDao();		
		
		ContatoForm contatoForm = (ContatoForm) form;
		
		Contato contato = new Contato();
		
		contato.setNome(contatoForm.getNome());
		contato.setEmail(contatoForm.getEmail());
		contato.setTelefone_cel(contatoForm.getTelefone_cel());
		contato.setTelefone_res(contatoForm.getTelefone_res());
		contato.setTelefone_outro(contatoForm.getTelefone_outro());
				
		if(contatoDao.adicionar(contato))
		{
			contatoForm.reset(map,request);
			return map.findForward("contatoSalvo");
		}
		
		return map.findForward("contatoNaoSalvo");
	}
	
	public ActionForward editar(ActionMapping map, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	{
		return map.findForward("");
	}
	
	public ActionForward remover(ActionMapping map, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		int contato_id = Integer.parseInt(request.getParameter("id"));
		
		ContatoDao contatoDao = new ContatoDao();
		
		if(!contatoDao.remover(contato_id))
		{
			return map.findForward("contatoNaoExcluido");
		}
		
		return map.findForward("contatoExcluido");
	}
	
	public ActionForward listar(ActionMapping map, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		ContatoDao contatoDao = new ContatoDao();
		
		List<Contato> listaContatos = contatoDao.listar();
		
		request.setAttribute("listaContatos", listaContatos);
		
		return map.findForward("listaContatos");
	}
}
//ContatoForm.java
package br.com.exemplo.controller.form;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.ValidatorForm;

public class ContatoForm extends ValidatorForm
{
	private static final long serialVersionUID = 1229658575670874669L;

	private Integer id;
	private String nome;
	private String email;
	private String telefone_res;
	private String telefone_cel;
	private String telefone_outro;
	private List listaContatos = new ArrayList();
	
	
	public List getContatos()
	{
		return listaContatos;
	}
	
	public void setContatos(List listaContatos)
	{
		this.listaContatos = listaContatos;
	}
	
	public String getEmail()
	{
		return email;
	}
	
	public void setEmail(String email)
	{
		this.email = email;
	}
	
	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 getTelefone_cel()
	{
		return telefone_cel;
	}
	
	public void setTelefone_cel(String telefone_cel)
	{
		this.telefone_cel = telefone_cel;
	}
	
	public String getTelefone_outro()
	{
		return telefone_outro;
	}
	
	public void setTelefone_outro(String telefone_outro)
	{
		this.telefone_outro = telefone_outro;
	}
	
	public String getTelefone_res()
	{
		return telefone_res;
	}
	
	public void setTelefone_res(String telefone_res)
	{
		this.telefone_res = telefone_res;
	}
	
	@Override
	public ActionErrors validate(ActionMapping map,	HttpServletRequest request) 
	{
		ActionErrors errors = super.validate(map, request);
		return(errors);
	}
	
}
//Contato.java
package br.com.exemplo.model.bean;

import java.io.Serializable;

public class Contato implements Serializable
{
	private static final long serialVersionUID = -9186450787801998666L;

	private int id;
	private String nome;
	private String email;
	private String telefone_res;
	private String telefone_cel;
	private String telefone_outro;

	public Contato()
	{
		
	}

	public int getId() 
	{
		return id;
	}

	public void setId(int id) 
	{
		this.id = id;
	}

	public String getNome() 
	{
		return nome;
	}

	public void setNome(String nome) 
	{
		this.nome = nome;
	}

	public String getEmail()
	{
		return email;
	}

	public void setEmail(String email)
	{
		this.email = email;
	}
	
	public String getTelefone_res()
	{
		return telefone_res;
	}

	public void setTelefone_res(String telefone_res)
	{
		this.telefone_res = telefone_res;
	}
	
	public String getTelefone_cel()
	{
		return telefone_cel;
	}

	public void setTelefone_cel(String telefone_cel)
	{
		this.telefone_cel = telefone_cel;
	}

	public String getTelefone_outro()
	{
		return telefone_outro;
	}

	public void setTelefone_outro(String telefone_outro)
	{
		this.telefone_outro = telefone_outro;
	}
}
//ContatoDao.java
package br.com.exemplo.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.com.exemplo.model.bean.Contato;
import br.com.exemplo.system.ConnectionManager;

public class ContatoDao 
{
	private Connection connection;
	
	public ContatoDao()
	{
		this.connection = new ConnectionManager().getConnection();
	}
	
	public boolean adicionar(Contato contato) throws SQLException
	{		
		PreparedStatement stmt = connection.prepareStatement("INSERT INTO contato (nome, email, telefone_res, telefone_cel, telefone_outro) values (?, ?, ?, ?, ?)");
		
		stmt.setString(1, contato.getNome());
		stmt.setString(2, contato.getEmail());
		stmt.setString(3, contato.getTelefone_res());
		stmt.setString(4, contato.getTelefone_cel());
		stmt.setString(5, contato.getTelefone_outro());
		
		if (stmt.executeUpdate() == 1)
		{
			stmt.close();
			
			return true;
		}
		
		stmt.close();
		
		
		return false;
	}
	
	public boolean remover(int contato_id) throws SQLException
	{
		PreparedStatement stmt = connection.prepareStatement("DELETE FROM contato where id = ?");
		
		stmt.setInt(1, contato_id);
		
		if(stmt.executeUpdate() == 1)
		{
			stmt.close();

			return true;
		}
		
		stmt.close();
	
		return false;
	}
	
	public boolean editar(Contato contato) throws SQLException
	{
		PreparedStatement stmt = connection.prepareStatement("UPDATE contato set nome = ?, email = ?, telefone_res = ?, telefone_cel = ?, telefone_outro = ? WHERE id = ?");
		
		stmt.setString(1, contato.getNome());
		stmt.setString(2, contato.getEmail());
		stmt.setString(3, contato.getTelefone_res());
		stmt.setString(4, contato.getTelefone_cel());
		stmt.setString(5, contato.getTelefone_outro());
		stmt.setInt(6, contato.getId());
		
		if(stmt.executeUpdate() == 1)
		{
			stmt.close();
			
						
			return true;
		}		

		stmt.close();
		
		
		return false;
	}
	
	public List<Contato> listar() throws SQLException
	{
		List<Contato> listaContatos = new ArrayList<Contato>(); 
			
		PreparedStatement stmt = connection.prepareStatement("SELECT * FROM contato");
		
		ResultSet resultSet = stmt.executeQuery();
		
		while (resultSet.next())
		{
			Contato contato = new Contato();
			
			contato.setId(resultSet.getInt("id"));
			contato.setNome(resultSet.getString("nome"));
			contato.setEmail(resultSet.getString("email"));
			contato.setTelefone_res(resultSet.getString("telefone_res"));
			contato.setTelefone_cel(resultSet.getString("telefone_cel"));
			contato.setTelefone_outro(resultSet.getString("telefone_outro"));
			
			listaContatos.add(contato);
		}

		stmt.close();

		return listaContatos;
	}
	
}
<!-- novoContato.jsp -->
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

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

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
		<title>Adicionar nova entrada na lista</title>
	</head>

	<body>
<html:errors />
		<html:form action="/contato">
	
			<html:hidden property="method" value="adicionar" />
	
			<label for="nome">Nome: </label>
			<br />
			<html:text name="contatoForm" property="nome" />
			<br />
			<label for="email">Email: </label>
			<br />
			<html:text name="contatoForm" property="email" />
			<br />
			<label for="telefone_res">Telefone: </label>
			<br />
			<html:text name="contatoForm" property="telefone_res" />
			<br />
			<label for="ramal">Celular: </label>
			<br />
			<html:text name="contatoForm" property="telefone_cel" />
			<br />
			<label for="tipo">Outro: </label>
			<br />
			<html:text name="contatoForm" property="telefone_outro" />
			<br />

			<html:submit />
		
			<html:link action="/contato.do?method=listar">listar</html:link>
		
		</html:form>
		
	</body>
</html>
<!-- listarContatos.jsp -->
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

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

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
		<title>Lista de contatos</title>
	</head>

	<body>
		<c:choose>
			<c:when test="${empty listaContatos}">
				Não há registros cadastrados.
			</c:when>
		
			<c:when test="${not empty listaContatos}">
				<ul>
					<c:forEach var="contato" items="${listaContatos}">
						<li>
							<html:link href="#" title="visualizar detalhes do contato">${contato.nome}</html:link> | <html:link action="editarContato.do?id=${contato.id}&amp;nome=${contato.nome}&amp;email=${contato.email}&amp;telefone_res=${contato.telefone_res}&amp;telefone_cel=${contato.telefone_cel}&amp;telefone_outro=${contato.telefone_outro}">#editar#</html:link> | <html:link action="contato.do?method=remover&id=${contato.id}">#excluir#</html:link>
						</li>
					</c:forEach>
				</ul>	
			</c:when>
		</c:choose>
		
		
	</body>
</html>
<!-- struts-config -->
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>

	<!-- -->
	<form-beans>
		<form-bean name="contatoForm"
			type="br.com.exemplo.controller.form.ContatoForm"
		/>
	</form-beans>

	<!-- -->
	<global-forwards>

	</global-forwards>
	<!-- -->

	<!-- -->
	<action-mappings>

		<!-- se eu usar o validate dá merda... -->
		<action path="/contato"
				type="br.com.exemplo.controller.action.ContatoAction"
				name="contatoForm" 
				input="/view/admin/novoContato.jsp"
				scope="request" 
				validate="false"  
				parameter="method">
				
			<forward name="contatoSalvo"
					 path="/view/admin/resultados/contatoSalvo.jsp" />
					 
			<forward name="contatoNaoSalvo"
					 path="/view/admin/resultados/contatoNaoSalvo.jsp" />
					 
			<forward name="contatoExcluido"
					 path="/view/admin/resultados/contatoExcluido.jsp" />
					 
		</action>
		
		<action path="/listarContatos"
				type="br.com.exemplo.controller.action.ListarContatosAction"
				scope="request">
				
			<forward name="listaContatos"
					 path="/view/admin/resultados/listarContatos.jsp" />

		</action>
		
		
		

	</action-mappings>

	<!-- -->
	<message-resources parameter="MessageResources" />

	<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
		<set-property 
			property="pathnames"
			value="/WEB-INF/validation.xml,
			/WEB-INF/validator-rules.xml" 
		/>
	</plug-in>
</struts-config>
<!-- validation.xml -->
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN" "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">

<form-validation>
    <global>
        <!-- An example global constant
        <constant>
            <constant-name>postalCode</constant-name>
            <constant-value>^\d{5}\d*$</constant-value>
        </constant>
        end example-->
    </global>
    
    <formset>
        <form name="contatoForm">
            <field property="nome" depends="required">
                <arg0 key="sistema.form.contato.nome"/>
            </field>
            
   			<field property="email" depends="required,email">
				<arg0 key="sistema.form.contato.email" />
			</field>
		</form>
    </formset>    
</form-validation>

1 Resposta

lgi2020

Ninguém pra me ajudar? :?

Criado 18 de maio de 2007
Ultima resposta 23 de mai. de 2007
Respostas 1
Participantes 1