Carregando formulário com Struts

Galera é o seguinte…

Eu quero quando chamar a pagina jsp já carregar nas combobox as cidades e os estados com struts…
como faço pra carregar já no inicio com struts os combobox?

Crie uma lista/array onde você terá as cidades.

no jsp, vc deve receber esta lista, do Action por exemplo, então utilize a tag
<logic:iterate>

Ou vc pode usar a taglib html:select do struts:

http://struts.apache.org/userGuide/struts-html.html#select

serve justamente pra isso

Alguém tem algum código como exemplo da jsp?

cara, no próprio mailreader que vem com o struts tem exemplos disso

Dê uma olhada neste post:

http://www.guj.com.br/posts/list/27424.java :wink:

Tá, um exemplo pra usar a tag html:select:

// Na action:

List pessoas = new ArrayList();
pessoas.add(new Pessoa(0, "Bruno"));
pessoas.add(new Pessoa(0, "Costa"));

request.setAttribute("pessoas", pessoas);

//Na JSP:

<html:select property="pessoa">
<html:options collection="pessoas" property="id" labelProperty="nome" />
</html:select>

Valeu galera…
só mais uma duvida…
assim que eu chamar a jsp ele não vai carregar não é…
como faço pra que junto com a chamada da jsp eu já faça a chamada da action pra carregar a combo?

Depende, se você mandar a lista com as UF´s - Estados - e construir o comboBox corretamente vai montar na hora que você chamou a página.

Faça com que o usuário tenha que acessar a action pra poder acessar a jsp… acesso direto a JSP não é legal (na minha opinião)…

inclusive, mesmo q uma jsp não precise de action, faça um

<action	path="/index"
 forward="index.jsp" />

Assim, ao invés de “linkar” para index.jsp, linke para index.do

ps: Essa action sem classe definida não resolve seu problema acima, você deve carregar as coleções no request ou na session antes de popular uma combobox com ela… :slight_smile:

como eu faço pra carregar elas na jsp…ou seja…eu não to conseguindo pegar elas na jsp…tentei usar o jsp:useBean mas não tá dando certo… tá tudo parado aqui…como faço pra usar …eu já setei na action…mas não to conseguindo capturar na jsp

Para pegar utilize:

&lt;%request.getAttribute("cidadeSet")%&gt;

Você deve settar no action assim:

request.setAttribute("cidadeSet", cidadeSet)

Diego,

Caso vc não tenha resolvido ainda, cole a jsp e a action aqui, talvez nos ajude a entender melhor o problema :slight_smile:

Dae galera voltando com o martirio

vou colar a Action, o struts-config e o jsp…pra tentar encontrar o erro…e vou colar o erro que tá dando

Action

package gastro.controller;

import gastro.beans.Distribuidor;
import gastro.form.DistribuidorForm;
import gastro.model.DistribuidorModel;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Vector;

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

/**
 * @author Diego
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class DistribuidorAction extends DispatchAction
{

    public ActionForward iniciar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        try{
        Collection listaEstados = DistribuidorModel.getEstados();
        Collection listaCidades = DistribuidorModel.getCidades();
        request.setAttribute("listaEstados", listaEstados);
        request.setAttribute("listaCidades", listaCidades);
        }catch(Exception e){
            System.out.print(e);
        }
        return mapping.findForward("iniciarDistribuidor");
    
    }
    
       
}

O Model:


package gastro.model;

import gastro.beans.Distribuidor;
import gastro.beans.Estado;
import gastro.beans.Cidade;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;


public class DistribuidorModel 
{
    
    public static boolean cadastraDistribuidor(Distribuidor distribuidor) throws SQLException
	{
		Connection conn = ConexaoDB.getConnection();
		Statement stm = conn.createStatement();
		String query = "";

		query = "insert into distribuidor (id_estado, id_cidade, nome_distribuidor, " +
				"endereco_distribuidor, complemento_distribuidor, cep_distribuidor, fone_distribuidor) " +
				"values (" + "'" + distribuidor.getIdEstado() + "'" + "," + "'" + 
									distribuidor.getIdCidade()+ "," + "'" +
									distribuidor.getNomeDistribuidor() + "," + "'" +
									distribuidor.getEnderecoDistribuidor() + "," + "'" +
									distribuidor.getComplementoDistribuidor() + "," + "'" +
									distribuidor.getCepDistribuidor() + "," + "'" +
									distribuidor.getFoneDistribuidor() + "'" + ")";
		
		System.out.println(query);
		return stm.executeUpdate(query) >= 1 ? true : false;		
	}
    
    public static Vector getEstados() throws SQLException
	{
		Connection conn = ConexaoDB.getConnection();
		Statement stm = conn.createStatement();
		ResultSet rs;
		Vector vEstados = new Vector();
		Estado estados = new Estado();
		
		try
		{

			rs = stm.executeQuery("select * from Estado");

			int colCount = rs.getMetaData().getColumnCount();
			
			
			while (rs.next())
			{
				estados.setIdEstado(rs.getString(1));
				estados.setNomeEstado(rs.getString(2));
				
				vEstados.add(estados);
			}

			rs.close();
			stm.close();

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return vEstados;
	}

    public static Vector getCidades() throws SQLException
	{
		Connection conn = ConexaoDB.getConnection();
		Statement stm = conn.createStatement();
		ResultSet rs;
		Vector vCidades = new Vector();
		Cidade cidades = new Cidade();
		
		try
		{

			rs = stm.executeQuery("select * from Cidade");

			int colCount = rs.getMetaData().getColumnCount();
			
			
			while (rs.next())
			{
			    cidades.setIdCidade(rs.getString(1));
				cidades.setIdEstado(rs.getString(2));
				cidades.setNomeCidade(rs.getString(3));
				
				vCidades.add(cidades);
			}

			rs.close();
			stm.close();

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return vCidades;
	}
    
    public static Vector getDistribuidores() throws SQLException
	{
		Connection conn = ConexaoDB.getConnection();
		Statement stm = conn.createStatement();
		ResultSet rs;
		Vector vDistribuidores = new Vector();
		
		try
		{

			rs = stm.executeQuery("select a.nome_distribuidor, a.endereco_distribuidor, " +
					"a.complemento_distribuidor, a.fone_distribuidor,  a.email_distribuidor,  " +
					"b.nome_cidade, c.nome_estado from distribuidor a, cidade b, estado c where " +
					"a.id_cidade = b.id_cidade and b.id_estado = c.id_estado " +
					"order by a.nome_distribuidor");

			int colCount = rs.getMetaData().getColumnCount();
			
			
			while (rs.next())
			{
				Distribuidor distribuidor = new Distribuidor();
				
				distribuidor.setNomeDistribuidor(rs.getString(1));
				distribuidor.setEnderecoDistribuidor(rs.getString(2));
				distribuidor.setComplementoDistribuidor(rs.getString(3));
				distribuidor.setFoneDistribuidor(rs.getString(4));
				distribuidor.setEmailDistribuidor(rs.getString(5));
				distribuidor.setNomeCidade(rs.getString(6));
				distribuidor.setNomeEstado(rs.getString(7));				
				
				vDistribuidores.add(distribuidor);
			}

			rs.close();
			stm.close();

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return vDistribuidores;
	}
}

O jsp

<%@ page import="org.apache.struts.action.ActionErrors" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<html>
<head>
<LINK REL=STYLESHEET TYPE="text/css" HREF="css1.css">
</head>

<html:errors property="<%=ActionErrors.GLOBAL_ERROR%>"/>

<html:form action="/CadastroDistribuidor">
<html:messages id="error" property="name">
<font color="red"><bean:write name="error"/></font>
</html:messages>
<p>Nome: <html:text property="strNomeDistribuidor"/>
<p>Endereço: <html:text property="strEndDistribuidor"/>
<p>Complemento: <html:text property="strCompDistribuidor"/>
<p>Estado:
<html:select property="listaEstados">
    <html:options collection="listaEstados" property="idEstado"
labelProperty="nomeEstado" />
</html:select>

<p>Cidade: 
<html:select property="listaCidades">
    <html:options collection="listaCidades" property="idCidade"
labelProperty="nomeCidade" />
</html:select>

		   
<p>CEP: <html:text property="strCepDistribuidor"/>
<p>Fone: <html:text property="strFoneDistribuidor"/>
<html:submit/>
</html:form>
</html>

E o 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">

<!--
     This is a blank Struts configuration file with an example
     welcome action/page and other commented sample elements.

     Tiles and the Struts Validator are configured using the factory defaults
     and are ready-to-use.

     NOTE: If you have a generator tool to create the corresponding Java classes
     for you, you could include the details in the "form-bean" declarations.
     Otherwise, you would only define the "form-bean" element itself, with the
     corresponding "name" and "type" attributes, as shown here.
-->


<struts-config>

<!-- ================================================ Form Bean Definitions -->

    <form-beans>
    
	<form-bean
            name="produtoForm"
            type="gastro.form.ProdutoForm"/>
            
    <form-bean
            name="distribuidorForm"
            type="gastro.form.DistribuidorForm"/>
            
    </form-beans>


<!-- ========================================= Global Exception Definitions -->

    <global-exceptions>
        <!-- sample exception handler
        <exception
            key="expired.password"
            type="app.ExpiredPasswordException"
            path="/changePassword.jsp"/>
        end sample -->
    </global-exceptions>


<!-- =========================================== Global Forward Definitions -->

    <global-forwards>
        <!-- Default forward to "Welcome" action -->
        <!-- Demonstrates using index.jsp to forward -->
        <forward
            name="welcome"
            path="/Welcome.do"/>  
            
       	<forward 
       		name="table" 
       		path="/Table.jsp" />
       		
        <forward 
       		name="iniciarDistribuidor" 
       		path="/cadastro_distribuidor.jsp" />
       		
    </global-forwards>

<!-- =========================================== Action Mapping Definitions -->

    <action-mappings>
            <!-- Default "Welcome" action -->
            <!-- Forwards to Welcome.jsp -->
        <action
            path="/Welcome"
            forward="/pages/Welcome.jsp"/>
        
            
       	<action path="/CadastroProduto" 
        		type="gastro.controller.ProdutoAction" 
        		scope="request" 
        		name="produtoForm" 
        		validate="false" 
        		input="/cadastro_produto.jsp" 
        		parameter="insereProduto">
        </action>
        
        <action path="/CadastroDistribuidor" 
        		type="gastro.controller.DistribuidorAction" 
        		scope="request" 
        		name="distribuidorForm" 
        		validate="false" 
        		parameter="acao">
        </action>
       
        
         <action path="/Oi" 
        		type="gastro.controller.Oi" 
        		scope="request" 
        		name="distribuidorForm" 
        		validate="false" 
        		parameter="acao">
        </action>


    </action-mappings>


<!-- ============================================= Controller Configuration -->

    <controller
       processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>


<!-- ======================================== Message Resources Definitions -->

    <message-resources parameter="MessageResources" />


<!-- =============================================== Plug Ins Configuration -->

  <!-- ======================================================= Tiles plugin -->
  <!--
     This plugin initialize Tiles definition factory. This later can takes some
	 parameters explained here after. The plugin first read parameters from
	 web.xml, thenoverload them with parameters defined here. All parameters
	 are optional.
     The plugin should be declared in each struts-config file.
       - definitions-config: (optional)
            Specify configuration file names. There can be several comma
		    separated file names (default: ?? )
       - moduleAware: (optional - struts1.1)
            Specify if the Tiles definition factory is module aware. If true
            (default), there will be one factory for each Struts module.
			If false, there will be one common factory for all module. In this
            later case, it is still needed to declare one plugin per module.
            The factory will be initialized with parameters found in the first
            initialized plugin (generally the one associated with the default
            module).
			  true : One factory per module. (default)
			  false : one single shared factory for all modules
	   - definitions-parser-validate: (optional)
	        Specify if xml parser should validate the Tiles configuration file.
			  true : validate. DTD should be specified in file header (default)
			  false : no validation

	  Paths found in Tiles definitions are relative to the main context.
  -->

    <plug-in className="org.apache.struts.tiles.TilesPlugin" >

      <!-- Path to XML definition file -->
      <set-property property="definitions-config"
                       value="/WEB-INF/tiles-defs.xml" />
      <!-- Set Module-awareness to true -->
      <set-property property="moduleAware" value="true" />
    </plug-in>


  <!-- =================================================== Validator plugin -->

  <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property
        property="pathnames"
        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
  </plug-in>

</struts-config>

A chamada da página é feita através da seguinte URL: CadastroDistribuidor.do?acao=iniciar

Galera e dá o seguinte erro:

Exception report

message 

description The server encountered an internal error () that prevented it from fulfilling this request.

exception 

javax.servlet.ServletException: No getter method available for property listaEstados for bean under name org.apache.struts.taglib.html.BEAN
	org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:825)
	org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:758)
	org.apache.jsp.cadastro_005fdistribuidor_jsp._jspService(cadastro_005fdistribuidor_jsp.java:195)
	org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
	org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1063)
	org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:263)
	org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:386)
	org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:318)
	org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:229)
	org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
	org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)


root cause 

javax.servlet.jsp.JspException: No getter method available for property listaEstados for bean under name org.apache.struts.taglib.html.BEAN
	org.apache.struts.taglib.html.SelectTag.calculateMatchValues(SelectTag.java:266)
	org.apache.struts.taglib.html.SelectTag.doStartTag(SelectTag.java:200)
	org.apache.jsp.cadastro_005fdistribuidor_jsp._jspx_meth_html_select_0(cadastro_005fdistribuidor_jsp.java:275)
	org.apache.jsp.cadastro_005fdistribuidor_jsp._jspService(cadastro_005fdistribuidor_jsp.java:157)
	org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
	org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1063)
	org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:263)
	org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:386)
	org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:318)
	org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:229)
	org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
	org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:802)


note The full stack trace of the root cause is available in the Apache Tomcat/5.0.28 logs.

Onde está o erro???

 <html:select property="listaEstados">
     <html:options collection="listaEstados" property="idEstado"
 labelProperty="nomeEstado" />
 </html:select>

Lá em <html:select property=“listaEstados”, esse listaEstados deveria na verdade ser a propriedade do action form à qual será retornada o valor escolhido na combobox… (estado provavelmente), entendeu? O mesmo vale pra “listaCidades”.

Acho que agora vai hein! :slight_smile:

bruno me perdoe a ignorância…mas não entendi!
como assim a propriedade da Action form?

Fala ae diegom ,

isso mesmo q brunocosta falou. A propriedade property de qualquer “<html: >” deve ser a propriedade relacionada no seu Form.

O erro “No getter method available for property listaEstados” mostra que não existe o metodo get() para esta propriedade, isso ocorre pq ela não é uma propriedade do seu form e sim uma lista/array com as cidades que você quer colocar no <select>.

mude e poste aqui caso dê algum novo erro ok? :thumbup:

isso ae! hehe :smiley:

diegom

Propriedade do Form é qualquer atributo do seu gastro.form.DistribuidorForm

entendi tranquilamente…
mas entao…eu teria que criar no meu Bean um atributo que eu colocasse o Vector?
como eu altero pra distribuir as cidades das listas?