Uso de colection

Ola pessoal, estou precisando visualizar (fazer uma lista de todos os usuários cadastrados no banco em uma pagina JSP). Eu gostaria de saber como e possível fazer isso?

Eu estou trabalhando no modelo MVC. Entao eu tenho o DTO, DAO, SERVLET e JSP. Se alguem puder me mandar uma explicação.

Esse e o meu codigo:

JSP

<%–
Document : listarFornecedor
Created on : 05/10/2010, 22:36:25
Author : Masterkey
–%>

<%@page import=“javax.swing.JOptionPane”%>
<%@page import=“java.text.SimpleDateFormat”%>
<%@page import=“modelo.FornecedorDTO”%>
<%@page import=“java.util.Iterator”%>
<%@page import=“java.util.Collection”%>
<%@page contentType=“text/html” pageEncoding=“UTF-8”%>

Lista de Fornecedores function editar(valor){ document.FrmManterFornecedor.acao.value = "editarDadosUsuario"; document.FrmManterFornecedor.id.value = valor;
           document.FrmManterFornecedor.submit();
        }
        function excluir(valor){
           document.FrmManterFornecedor.acao.value = "excluirUsuario";
           document.FrmManterFornecedor.id.value   = valor;

           document.FrmManterFornecedor.submit();
        }
    </script>


</head>
<%
   String msgErro    = (String)request.getSession().getAttribute("msgErro");
   String msgSucesso = (String)request.getSession().getAttribute("msgSucesso");
   if(msgErro != null){
%>
<%= msgErro %><br>
<%
    }
   if(msgSucesso != null){
 %>
 <%= msgSucesso %><br>
 <%
    }
  %>



<body>
    <form name="FrmManterFornecedor" action="/ProjetoOriginal/ControleFornecedor" method="post">

        <input type="hidden" name="acao" value=""/>
        <input type="hidden" name="id" value=""/>

    <h1 align="center">Manter Fornecedor - Lista de Fornecedores Cadastrados no Sistema</h1>

    <table align="center" border="1" cellpadding="0" cellspacing="0" width="100%" class="">
        <tr>
            <th width="36%" align="center">Nome do Fornecedor</th>
            <th width="15%" align="center">Endereco</th>
            <th width="15%" align="center">CPF</th>
            <th width="15%" align="center">Email</th>
            
        </tr>


        <%
          Collection lista = (Collection) request.getSession().getAttribute("listarFornecedores");


    [i]//Mas especificamente aqui é minha duvida.[/i]

              if(!lista.isEmpty()){
    JOptionPane.showMessageDialog(null, "Estou aki");

  
              Iterator it = lista.iterator();
              while(it.hasNext()){
                FornecedorDTO dto = (FornecedorDTO)it.next();
        %>



        <tr>
            <td width="35%" align="left">&nbsp;&nbsp;<%= dto.getNome().trim().toUpperCase() %></td>
            <td width="15%" align="left">&nbsp;&nbsp;<%= dto.getEndereco().trim().toUpperCase() %></td>
            
            <td width="15%" align="left">&nbsp;&nbsp;<%= dto.getCpf() %></td>
            <td width="5%" align="center"><%= dto.getEmail().trim().toUpperCase() %></td>
            
                <a href="javascript:editar(<%= dto.getId() %>)">
                  <img src="../img/document_edit.png" alt="Editar dados do fornecedor."/>
                </a>
            </td>
            <td width="7%" align="center">
                <a href="javascript:excluir(<%= dto.getId() %>)">
                  <img src="../img/cancel.png" alt="Excluir fornecedor."/>
                </a>
            </td>
        </tr>
        <%
            }
          }
        %>

    </table>
    <%
        if(lista.isEmpty()){
    %>
    <table align="center" border="1" cellpadding="0" cellspacing="0" class="" width="100%">
        <tr>
            <td>Atenção! Não existe Fornecedor cadastrado na base de dados.</td>
        </tr>
    </table>
    <%
        }
     %>
     <br>
   <!-- Criando os botões -->
   <table align="center" border="0" cellpadding="0" cellspacing="0" class="" width="20%">
        <tr>
            <td align="center" width="10%">
                <a href="/ProjetoOriginal/ControleFornecedor?acao=exibirIncluirFornecedor">
                     <img src="../img/incluirUsuario.gif" alt="Incluir fornecedor"/>
                </a>
            </td>
            <td align="center" width="10%">
                <a href="/ProjetoOriginal/SGGC.html">
                    <img src="../img/voltar.gif" alt="Voltar para página principal"/>
                </a>
            </td>
        </tr>
    </table>
    </form>
</body>

SERVLET

package controle;

/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import modelo.FornecedorDTO;
import persistencia.FornecedorDAO;

/**
*

  • @author Masterkey
    */
    public class ControleFornecedor extends HttpServlet {

    private String nome;
    private String cpf;
    private String incEstadual;
    private String endereco;
    private String nr;
    private String complemento;
    private String bairro;
    private String cidade;
    private String estado;
    private String telComercial;
    private String telCelular;
    private String email;
    private String acao;
    //private String id;
    private FornecedorDAO dao;
    private FornecedorDTO dto;
    private String msgSucesso;
    private String msgErro;

    private String NEXT_PAGE;
    private static final String FORWARD_MANTER_FORNECEDOR = “manterFornecedor.jsp”;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, Exception {
    response.setContentType(“text/html;charset=UTF-8”);

     this.acao = request.getParameter("acao");
     this.nome = request.getParameter("nome");
     //this.cpf = request.getParameter("cnpj");
    //JOptionPane.showMessageDialog(null, "A mensagem e: " + nome);
    //JOptionPane.showMessageDialog(null, "A acao e: " + acao);
    
     //popularAtributosApartirDoJSP(request);
     msgSucesso = null;
     msgErro = null;
    
     try{
         //popularAtributosApartirDoJSP(request);
    
             if(acao.equalsIgnoreCase("pesquisarFornecedorPorNome")){
                 JOptionPane.showMessageDialog(null, "A mensagem e: " + nome);
                 JOptionPane.showMessageDialog(null, "A acao e: " + acao);
                 
                 
    
    
    
    
    
    
    
                 msgErro = "Atencao! Fornecedor cadastrado com sucesso.";
                 request.setAttribute("msgErro", msgErro);
                 request.setAttribute("msgSucesso", null);
                 RequestDispatcher rd = request.getRequestDispatcher("/ManterFornecedor.jsp");
                 rd.forward(request, response);
                 
                
              this.dao = FornecedorDAO.createInstance();
              dao.recuperarFornecedorPorNome(nome);
              JOptionPane.showMessageDialog(null, "Estou aqui");
    
              
             }
    

if(acao.equalsIgnoreCase(“SalvarFornecedor”)){
JOptionPane.showMessageDialog(null, “Estou aqui”);

}

    if(acao.equalsIgnoreCase("incluir")){
        JOptionPane.showMessageDialog(null, "Estou aqui");



    }

    /*if(acao.equalsIgnoreCase("salvarInclusao")){
             //-- Colocando o dto na sessão e preechendo o dto --//
            // this.colocandoDTOPreenchidoNaSessao(request);

             //-- Salvando o novo usuário --//
             this.dao = FornecedorDAO.createInstance();
        try {
            if (this.dao.incluirFornecedor(this.dto)) {
                this.msgSucesso = "Atenção! O novo usuario foi incluído com sucesso.";
                request.getSession().setAttribute("msgSucesso", this.msgSucesso);
                Collection lista = this.dao.recuperarTodosFornecedores();
                request.getSession().setAttribute("listarFornecedores", lista);
               // NEXT_PAGE = FORWARD_MANTER_USUARIO;
            } else {
                this.msgErro = "Atenção! Não foi possível incluir o novo usuário, verifique a sua rotina.";
                request.getSession().setAttribute("msgErro", this.msgErro);
              //  NEXT_PAGE = FORWARD_INCLUIR_USUARIO;
                RequestDispatcher rd = request.getRequestDispatcher("/manterFornecedor.jsp");
                rd.forward(request, response);

            }
        } catch (Exception ex) {
            Logger.getLogger(ControleFornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
         }
     * 
     */

if(acao.equalsIgnoreCase(“excluirUsuario”)){
String id = request.getParameter(“id”);

             this.dao = FornecedorDAO.createInstance();

             if(this.dao.excluirFornecedor(new Integer(cpf))){
                this.msgSucesso = "Atenção! O fornecedor selecionado foi excluído com sucesso";

                request.getSession().setAttribute("msgSucesso", this.msgSucesso);

                Collection lista = this.dao.recuperarTodosFornecedores();
                request.getSession().setAttribute("listarFornecedores", lista);

                //NEXT_PAGE = FORWARD_MANTER_FORNECEDOR;
                RequestDispatcher rd = request.getRequestDispatcher("/manterFornecedor.jsp");
                rd.forward(request, response);


             }else{
                this.msgErro = "Atenção! Não foi possível excluir o usuário informado, verifique a sua rotina.";

                request.getSession().setAttribute("msgErro", this.msgErro);

                Collection lista = this.dao.recuperarTodosFornecedores();
                request.getSession().setAttribute("listarFornecedores", lista);

                //NEXT_PAGE = FORWARD_MANTER_FORNECEDOR;
                RequestDispatcher rd = request.getRequestDispatcher("/manterFornecedor.jsp");
                rd.forward(request, response);

             }
         }

}catch(Exception e){
msgErro = “dsafsd”;
e.printStackTrace();

    }





    PrintWriter out = response.getWriter();
    try {
        /* TODO output your page here
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet ControleAnimal</title>");  
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet ControleAnimal at " + request.getContextPath () + "</h1>");
        out.println("</body>");
        out.println("</html>");
        */
    } finally { 
        out.close();
    }
}





public void popularAtributosApartirDoJSP(HttpServletRequest request){
    //-- Populando os atributos --//
    this.bairro       = request.getParameter("bairro");
    this.cidade       = request.getParameter("cidade");
    this.complemento  = request.getParameter("complemento");
    this.cpf         = request.getParameter("cpf");
    this.email        = request.getParameter("email");
    this.endereco     = request.getParameter("endereco");
    this.estado       = request.getParameter("estado");
    this.incEstadual    = request.getParameter("incEstadual");
    this.nome        = request.getParameter("nome");
    this.nr          = request.getParameter("nr");
    this.telCelular     = request.getParameter("telCelular");
    this.telComercial   = request.getParameter("telComercial");
    this.acao         = request.getParameter("acao");

// this.id = request.getParameter(“id”)

}

//
/**
* Handles the HTTP GET method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (Exception ex) {
Logger.getLogger(ControleFornecedor.class.getName()).log(Level.SEVERE, null, ex);
}
}

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (Exception ex) {
        Logger.getLogger(ControleFornecedor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/** 
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

DAO

package persistencia;

import modelo.FornecedorDTO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.JOptionPane;

public class FornecedorDAO {

private ResultSet rs;
private PreparedStatement stm;
private Connection conn;



public static FornecedorDAO createInstance(){

return new FornecedorDAO();
}


/*public boolean incluirFornecedor(final FornecedorDTO dto)throws Exception{
   boolean incluiu = true;
   conn = null;
    stm = null;
     rs = null;
    try {
        conn = Conexao.criaConexao();
        conn.setAutoCommit(false);//Pego a responsabilidade do banco de dados
         stm = conn.prepareStatement("Inserir aqui o script SQL para inclusao do Fornecedor");
         stm.setString(1, dto.getCidade());
         stm.setString(2, dto.getComplemento());
         stm.setString(3, dto.getCpf());
         stm.setString(4, dto.getEmail());
         stm.setString(5, dto.getEndereco());
         stm.setString(6, dto.getEstado());
         stm.setString(6, dto.getFoneCelular());
         stm.setString(6, dto.getFoneComercial());
         stm.setString(6, dto.getId());

       if(stm.executeUpdate() < 1){
          incluiu = false;
       }else{
          incluiu = true;
          conn.commit();//Estou mandando gravar de fato.
       }
    } catch (SQLException e) {
          e.printStackTrace();
          conn.rollback();
          throw new Exception(e.getLocalizedMessage(), e);
    }finally{
          conn.setAutoCommit(true);
          Conexao.fecharConexao(rs, stm, conn);
    }
   //-- retornando o resultado do incluiur --//
   return incluiu;
}
 *
 */

public Collection recuperarTodosFornecedores()throws Exception{
  rs   = null;
  stm  = null;
  conn = null;

  JOptionPane.showMessageDialog(null, "Estou");
  ArrayList<FornecedorDTO> lista = new ArrayList<FornecedorDTO>();
  try {
    


       conn = Conexao.criaConexao();
        stm = conn.prepareStatement("SELECT id, nome, cpf, inscestadual, email FROM primeiro.fornecedor ORDER BY nome");
         rs = stm.executeQuery();
       while(rs.next()){
          FornecedorDTO dto = this.popularDTO(rs);
          lista.add(dto);
       }
  } catch (SQLException e) {
    e.printStackTrace();
    JOptionPane.showMessageDialog(null, "estou aki");
    throw new Exception(e.getLocalizedMessage(), e);
  }finally{
     Conexao.fecharConexao(rs, stm, conn);
  }
  //-- retornando a coleção --//
  return lista;
}

protected FornecedorDTO popularDTO(ResultSet rs)throws Exception{


  //Falta colocar os atributos do bacno.
  return new FornecedorDTO(rs.getInt("id"), rs.getString("nome"), rs.getInt("cpf"),
                         rs.getInt("inscestadual"), rs.getString("email"));




}



public FornecedorDTO recuperarFornecedorPorNome(final String nomeFornecedor)throws Exception{
   conn = null;
    stm = null;
     rs = null;
   FornecedorDTO dto = null;
    try {
        conn = Conexao.criaConexao();
         stm = conn.prepareStatement("Aqui o Script para recumperar por id");
         stm.setString(1, nomeFornecedor);
          rs = stm.executeQuery();
        if(rs.next()){
           dto = this.popularDTO(rs);
        }
    } catch (SQLException e) {
       e.printStackTrace();
       throw new Exception(e.getLocalizedMessage(), e);
    }finally{
       Conexao.fecharConexao(rs, stm, conn);
    }
   //-- Retornando o objeto dto --//
   return dto;
}

/* public boolean alterarDadosFornecedor(final FornecedorDTO dto)throws Exception{
boolean alterou = true;
conn = null;
stm = null;
rs = null;
try {
conn = Conexao.criaConexao();
conn.setAutoCommit(false);
stm = conn.prepareStatement(“Aqui o Script para alterar o Fornecedor”);
stm.setString(1, dto.getCidade());
stm.setString(2, dto.getComplemento());
stm.setString(3, dto.getCpf());
stm.setString(4, dto.getEmail());
stm.setString(5, dto.getEndereco());
stm.setString(6, dto.getEstado());
stm.setString(6, dto.getFoneCelular());
stm.setString(6, dto.getFoneComercial());
stm.setString(6, dto.getId());

          if(stm.executeUpdate() < 1){
           alterou = false;
        }else{
           alterou = true;
           conn.commit();
        }

    } catch (SQLException e) {
       e.printStackTrace();
       conn.rollback();
       throw new Exception(e.getLocalizedMessage(), e);
    }finally{
       conn.setAutoCommit(true);
       Conexao.fecharConexao(rs, stm, conn);
    }
   //-- retornando o resultado da alteração --//
   return alterou;
}

*/

public boolean excluirFornecedor(final int idUsuario)throws Exception{
conn = null;
stm = null;
rs = null;
boolean excluiu = true;
try {
conn = Conexao.criaConexao();
conn.setAutoCommit(false);
stm = conn.prepareStatement(“Aqui o Script para excluir o Fornecedor”);
stm.setInt(1, idUsuario);
if(stm.executeUpdate() < 1){
excluiu = false;
}else{
excluiu = true;
conn.commit();
}
} catch (SQLException e) {
e.printStackTrace();
conn.rollback();
throw new Exception(e.getLocalizedMessage(), e);
}finally{
conn.setAutoCommit(true);
Conexao.fecharConexao(rs, stm, conn);
}
//-- Retornando o resultado da exclusão do usuário --//
return excluiu;
}

}

DTO

package modelo;

public class FornecedorDTO {

private int id;
private String nome;
private int cpf;
private int inscEstadual;
private String endereco;
private String nr;
private String complemento;
private String cidade;
private String estado;
private String foneComercial;
private String foneCelular;
private String email;



        //Construtor padrao
        public FornecedorDTO(){}

/*public FornecedorDTO( final String id, final String nome, final String cpf, final String inscEstadual, final String endereco, final String nr,
        final String complemento, final String cidade, final String estado, final String foneComercial, final String foneCelular, final String email) {

    this.id = id;
    this.nome = nome;
    this.cpf = cpf;
    this.inscEstadual = inscEstadual;
    this.endereco = endereco;
    this.nr = nr;
    this.complemento = complemento;
    this.cidade = estado;
    this.foneComercial = foneComercial;
    this.foneCelular = foneCelular;
    this.email = email;
}*/
public FornecedorDTO( final int id, final String nome, final int cpf, final int inscricao, final String email) {

    this.id = id;
    this.nome = nome;
    this.cpf = cpf;
    this.inscEstadual = inscricao;
    this.email = email;
}

public static FornecedorDTO createInstance(){

return new FornecedorDTO();
}

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 int getCpf() {
    return cpf;
}

public void setCpf(int cpf) {
    this.cpf = cpf;
}

public int getInscEstadual() {
    return inscEstadual;
}

public void setInscEstadual(int inscEstadual) {
    this.inscEstadual = inscEstadual;
}

public String getEndereco() {
    return endereco;
}

public void setEndereco(String endereco) {
    this.endereco = endereco;
}

public String getNr() {
    return nr;
}

public void setNr(String nr) {
    this.nr = nr;
}

public String getComplemento() {
    return complemento;
}

public void setComplemento(String complemento) {
    this.complemento = complemento;
}

public String getCidade() {
    return cidade;
}

public void setCidade(String cidade) {
    this.cidade = cidade;
}

public String getEstado() {
    return estado;
}

public void setEstado(String estado) {
    this.estado = estado;
}

public String getFoneComercial() {
    return foneComercial;
}

public void setFoneComercial(String foneComercial) {
    this.foneComercial = foneComercial;
}

public String getFoneCelular() {
    return foneCelular;
}

public void setFoneCelular(String foneCelular) {
    this.foneCelular = foneCelular;
}

public String getEmail() {
    return email;
}

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

}

VARIAVEIS DO BANCO DE DADOS

int id;
nome;
cpf;
inscestadual;
endereco;
nr;
complemento;
cidade;
estado;
fonecomercial;
fonecelular;
email;