Carregar formulário para alterar dados MVC

5 respostas
F

Boa tarde pessoal,

Olha eu aqui novamente,

Preciso mais uma vez da força de vocês para o seguinte problema.

Tenho uma página (jsp) que está listando todos os dados do banco. Nesta listagem existem dois links (ALTERAR E EXCLUIR).

Quando clico no link ALTERAR eu quero que ele carregue os dados em um formulário para alterar.

É nesta parte que está dando erro. Quando clico em ALTERAR ele vai direto para a minha página de erro.jsp.

Por favor, pessoal tem como me ajudar mais uma vez e me mostrar onde estou errando.

Muito obrigado.

Meu Bean

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

package com.romafa.bean;

/**
 *
 * @author Fabiano
 */
public class TipoLivroBean {
    
    private int idTipoLivro;
    private String nome;
    private AdministradorBean adminstrador;

    public String getNome() {
        return nome;
    }

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

    public int getIdTipoLivro() {
        return idTipoLivro;
    }

    public void setIdTipoLivro(int idTipoLivro) {
        this.idTipoLivro = idTipoLivro;
    }

    public AdministradorBean getAdminstrador() {
        return adminstrador;
    }

    public void setAdminstrador(AdministradorBean adminstrador) {
        this.adminstrador = adminstrador;
    }
    

}

Meu Dao

package com.romafa.dao;

import java.sql.Connection;
import com.romafa.bean.TipoLivroBean;
import com.romafa.conexao.Conexao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Fabiano
 */
public class TipoLivroDAO {
    
    public boolean adicionaTipoLivro (TipoLivroBean tipoLivroBean) throws SQLException{
    
        Connection conn = null;
        PreparedStatement ps = null;
                
        try {
          
            conn = Conexao.getConexao();         
            
            String insere = "INSERT INTO tipo_livro (administrador_idadministrador, tipNome) VALUES (?, ?)";

            ps = conn.prepareStatement(insere);
           
            ps.setInt(1, tipoLivroBean.getAdminstrador().getIdAdmin());
            ps.setString(2, tipoLivroBean.getNome());

            ps.executeUpdate();

            return true;       
           
        } catch (Exception e) {
            
            
            ps.close();
            conn.close();
            return false;
        }
        
        finally
        {
            
            
            ps.close();
            conn.close();
        
        }
        
    }
    
    public boolean recuperaTipoLivro (TipoLivroBean tipoLivroBean) throws SQLException
    {
        
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        
        try {
            
            conn = Conexao.getConexao();
            
            // sql para recuperar o tipo do livro pelo seu id
            String sql = "SELECT * FROM tipo_livro WHERE idtipo_livro = ?";
            ps = conn.prepareStatement(sql);

            ps.setInt(1, tipoLivroBean.getIdTipoLivro());

            rs = ps.executeQuery();

            if(rs.next())
            {
                
                tipoLivroBean.setIdTipoLivro(rs.getInt("idtipo_livro "));
                tipoLivroBean.setNome(rs.getString("tipNome "));
                
                return true;
            }
                else
            {
                return false;
            }
            
                
        } catch (Exception e) {
            
            rs.close();
            ps.close();
            conn.close();
            return false;
        }
        
        finally
        {
            ps.close();
            conn.close();
        }
    }
    
    public boolean alteraTipoLivro (TipoLivroBean tipoLivroBean) throws SQLException{
    
        Connection conn = null;
        PreparedStatement ps = null;
                
        try {
          
            conn = Conexao.getConexao();         
            
            String altera = "UPDATE tipo_livro SET tipNome = ? WHERE idtipo_livro = ?";

            ps = conn.prepareStatement(altera);
           
            ps.setString(1, tipoLivroBean.getNome());
            ps.setInt(2, tipoLivroBean.getIdTipoLivro());

            ps.executeUpdate();

            return true;       
           
        } catch (Exception e) {
            
            
            ps.close();
            conn.close();
            return false;
        }
        
        finally
        {
            
            ps.close();
            conn.close();
        
        }
        
    }
    
    public List<TipoLivroBean> listaTipoLivro() throws SQLException {

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        String sql = "SELECT * FROM tipo_livro ORDER BY tipNome";

        conn = Conexao.getConexao();
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();

        List<TipoLivroBean> tipLivros = new ArrayList<TipoLivroBean>();

        while (rs.next()) {
            TipoLivroBean tipLivro = new TipoLivroBean();

            tipLivro.setIdTipoLivro(rs.getInt("idtipo_livro"));
            tipLivro.setNome(rs.getString("tipNome"));

            tipLivros.add(tipLivro);

        }

        rs.close();
        ps.close();
        conn.close();

        return tipLivros;
    }
    
}

Meu Servlet

package com.romafa.controller;

import com.romafa.bean.TipoLivroBean;
import com.romafa.dao.TipoLivroDAO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Fabiano
 */
public class AlteraTipoLivroServlet extends HttpServlet {
   
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
        
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        
        RequestDispatcher rd;
        
        TipoLivroBean tipoLivroBean = new TipoLivroBean();
        
        String idTipoLivro = request.getParameter("idTipoLivro");

        tipoLivroBean.setIdTipoLivro(Integer.valueOf(idTipoLivro));
        
        TipoLivroDAO tipoLivroDao = new TipoLivroDAO();
        
        try {
            
            if(tipoLivroDao.recuperaTipoLivro(tipoLivroBean))
            {
                             
                request.setAttribute("categoriaLivro", tipoLivroDao);
                rd = request.getRequestDispatcher("/alterarTipoLivro.jsp");
                rd.forward(request, response);           
            }
            else
            {
                rd = request.getRequestDispatcher("/erro.jsp");
                rd.forward(request, response);
            }
        } catch (Exception e) {
            
            e.printStackTrace();
        }
                
    }
    
}

Meu jsp de listagem

<%@page contentType="text/html; charset=utf-8" language="java" session="true"%>
<%@page import="com.romafa.bean.TipoLivroBean,java.util.List"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>::: ROMAFA BOOK STORE :::</title>

<link href="estilo/estilo.css" rel="stylesheet" type="text/css" />

</head>

<body>
    
<table width="1024" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td><img src="img/logo.jpg" width="1024" height="81" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>
    <%@include file="menuAdmin.jsp" %>
    </td>
  </tr>
  <tr>
    <td><img src="img/banner.jpg" width="1024" height="159" /></td>
  </tr>
  <tr>
    <td><%= session.getAttribute("ID") %></td>
  </tr>
  <tr>
    <td>
        
      
        <table width="50%" border="0" align="center">
          <tr>
            <td colspan="2">listagem tipo Livro</td>
          </tr>
          <tr>
            <td width="79%">NOME</td>
            <td width="21%">ACAO</td>
          </tr>
          <%    
    		List <TipoLivroBean> listagem = (List)request.getAttribute("listTipoLivro");
			
			for(int i=0; i < listagem.size(); i++)

            {

        %>       

        
          <tr>
            <td><%= ((TipoLivroBean)listagem.get(i)).getNome() %></td>
            <td><a href="AlteraTipoLivroServlet?action=AlteraTipoLivroServlet&idTipoLivro=<%= ((TipoLivroBean)listagem.get(i)).getIdTipoLivro() %>">[Alterar]</a> <a href="ExluirTipoLivroServlet?action=ExluirTipoLivroServlet&idTipoLivro=<%= ((TipoLivroBean)listagem.get(i)).getIdTipoLivro() %>">[Excluir]</a></td>
          </tr>
          <%} %>
          
          <tr>
            <td colspan="2" align="center"><input name="Submit" type="button"  onClick="location.href='cadastrarTipoLivro.jsp'" value="Cadastrar categoria de Livros" /></td>
          </tr>
        </table>
    </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td align="center"><img src="img/rodape_adm.jpg" /></td>
  </tr>
</table>
</body>
</html>

Meu jsp do formulário de alteração que deve recuperar os dados

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" session="true" %>
<%@page import="com.romafa.bean.TipoLivroBean, com.romafa.dao.TipoLivroDAO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%

TipoLivroBean categoriaLivro;

categoriaLivro = (TipoLivroBean) request.getAttribute("categoriaLivro");

%>


<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>::: ROMAFA BOOK STORE :::</title>

<link href="estilo/estilo.css" rel="stylesheet" type="text/css" />

</head>

<body>
<table width="1024" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td><img src="img/logo.jpg" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>
    <%@include file="menuAdmin.jsp" %>
    </td>
  </tr>
  <tr>
    <td><img src="img/banner.jpg" width="1024" height="159" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td valign="top"><form id="form1" name="alteraTipoLivro" method="post" action="TipoLivroServlet">
      <table width="41%" border="0" align="center">
        <tr>
          <td colspan="2">CADASTRAR TIPO DO LIVROS</td>
          </tr>
        <tr>
          <td width="19%">NOME:</td>
          <td width="81%"><input name="tipNome" type="text" id="tipNome" size="40" maxlength="60" value="<%= categoriaLivro.getNome()%>" /></td>
        </tr>
        <tr>
          <td colspan="2" align="center"><input type="submit" name="button" id="button" value="Enviar" />
            <input type="reset" name="button2" id="button2" value="Limpar" /></td>
          </tr>
      </table>
    </form></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td align="center"><img src="img/rodape_adm.jpg" /></td>
  </tr>
</table>
</body>
</html>

Meu Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>AdministradorServlet</servlet-name>
        <servlet-class>com.romafa.controller.AdministradorServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>AdministradorServlet</servlet-name>
        <url-pattern>/AdministradorServlet</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>CadastrarTipoPagamento</servlet-name>
        <servlet-class>com.romafa.controller.CadastrarTipoPagamento</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CadastrarTipoPagamento</servlet-name>
        <url-pattern>/CadastrarTipoPagamento</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>ListarTipoPagamentoServlet</servlet-name>
        <servlet-class>com.romafa.controller.ListarTipoPagamentoServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ListarTipoPagamentoServlet</servlet-name>
        <url-pattern>/ListarTipoPagamentoServlet</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>ListarTipoLivroServlet</servlet-name>
        <servlet-class>com.romafa.controller.ListarTipoLivroServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>ListarTipoLivroServlet</servlet-name>
        <url-pattern>/ListarTipoLivroServlet</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>CadastrarTipoLivroServlet</servlet-name>
        <servlet-class>com.romafa.controller.CadastrarTipoLivroServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CadastrarTipoLivroServlet</servlet-name>
        <url-pattern>/TipoLivroServlet</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>AlteraTipoLivroServlet</servlet-name>
        <servlet-class>com.romafa.controller.AlteraTipoLivroServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AlteraTipoLivroServlet</servlet-name>
        <url-pattern>/AlteraTipoLivroServlet</url-pattern>
    </servlet-mapping>
    
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

5 Respostas

drsmachado

Mas qual é o erro, Lombardi?

jorgeneto

Vc já tentou depurar teu servlet?

F

Pessoal,

Obrigado pela força

Alterei a linha no meu servlet que estava

tipoLivroBean.setIdTipoLivro(Integer.valueOf(idTipoLivro));

para

tipoLivroBean.setIdTipoLivro(Integer.parseInt(idTipoLivro));

e ao depurar a minha Servlet apareceu a seguinte mensagem de erro

HTTP Status 500 - 

--------------------------------------------------------------------------------

type Exception report

message 

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

exception 

java.lang.NumberFormatException: null
	java.lang.Integer.parseInt(Integer.java:417)
	java.lang.Integer.parseInt(Integer.java:499)
	com.romafa.controller.AlteraTipoLivroServlet.doGet(AlteraTipoLivroServlet.java:34)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
	org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)


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

Isso indica que alguma ação envolvendo conversão para número não recebeu parâmetro ou ele tem valor null.

F

Estou convertendo o meu id desta forma

Link

<a href="AlteraTipoLivroServlet?action=AlteraTipoLivroServlet&idTipoLivro=<%= ((TipoLivroBean)listagem.get(i)).getIdTipoLivro() %>">[Alterar]</a>

Servlet

TipoLivroBean tipoLivroBean = new TipoLivroBean();
        
 String idTipoLivro = request.getParameter("idTipoLivro");
        
 tipoLivroBean.setIdTipoLivro(Integer.parseInt(idTipoLivro));

Não entendo onde está o erro.

Criado 3 de junho de 2011
Ultima resposta 3 de jun. de 2011
Respostas 5
Participantes 3