NullPointerException

6 respostas
T

Galera, sei que é um erro idiota, sem comentários…

Estou com um formulario em struts, que adiciona e exclui(teóricamente) os cadastrados…
Consigo incluir numa boa… mas quando eu clico em excluir, ele tá passando algum parametro nulo na action…
Coloco o mouse em cima do link (Remover) e ele passa a url com o id que eu quero apagar, mas não ta deletando…

Deem uma olha ai por favor…

RemoveContatoAction

package br.com.thiago.struts.action;

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

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 br.com.thiago.jdbc.dao.ContatoDAO;
import br.com.thiago.jdbc.modelo.Contato;
import br.com.thiago.struts.form.RemoveContatoForm;

public class RemoveContatoAction extends Action{
	
	@Override
	public ActionForward execute(ActionMapping map, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
				
		System.out.println("Removendo o Contato...");
		
		Contato contato = ((RemoveContatoForm) form).getContato();
		new ContatoDAO().remove(contato);
		
		return map.findForward("remove");
		
		
		
	}

}

novo.jsp

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<html:html>
<head><title>Sistema de Teste do Struts</title></head>
<html:errors/>
<html:form action="/novoContato">
	
	<table>
		<tr>
			<td>Nome:</td>
			<td><html:text property="contato.nome"/></td>
		</tr>
		
		<tr>
			<td>Email:</td>
			<td><html:text property="contato.email"/></td>
		</tr>
		
		<tr>
			<td></td>
			<td><html:submit>Enviar dados</html:submit></td>
		</tr>
	</table>
	
</html:form>
</html:html>

lista.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
<title>Dados Gravados!!!</title>  
<script>  
  var carregado = true;  
  var sucesso = true;  
    function alerta()
    {  
    	alert('Gravação realizada com sucesso !!!');   
    	window.close();  
  	}  
    
</script>  
</head>  
<body onLoad="alerta()">

<b>Contatos Gravados no Banco</b><br><br>
	<table border="1">
			<tr>
				<td><b>ID</b></td>
				<td><b>Nome</b></td>
				<td><b>Email</b></td>
			</tr>
			
		<c:forEach var="contato" items="${contatos}">
			
			<tr>
				<td>${contato.id}</td>
				<td>${contato.nome}</td>
				<td>${contato.email}</td>
				<td>(<a href="removeContato.do?contato.id=${contato.id}">remover</a>)</td>
			</tr>	
		</c:forEach>
	</table>
</body>  
</html>

ContatoDAO

package br.com.thiago.jdbc.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.thiago.jdbc.ConnectionFactory;
import br.com.thiago.jdbc.modelo.Contato;

public class ContatoDAO {

	private Connection connection;

	public ContatoDAO() throws SQLException {
		this.connection = ConnectionFactory.getConnection();
	}

	public void adiciona(Contato contato) throws SQLException {
		PreparedStatement stmt = this.connection
				.prepareStatement("insert into contatos (nome,email) values (?, ?)");

		stmt.setString(1, contato.getNome());
		stmt.setString(2, contato.getEmail());

		stmt.execute();
		stmt.close();
	}

	public void remove(Contato contato) throws SQLException {
		
		PreparedStatement stmt = this.connection
			.prepareStatement("delete from contatos where id = ?");
		
		stmt.setLong(1, contato.getId());
		
		stmt.executeUpdate();
		stmt.close();
}

	public List<Contato> getLista() throws SQLException {

		PreparedStatement stmt = this.connection
				.prepareStatement("select * from contatos");
		ResultSet rs = stmt.executeQuery();

		List<Contato> contatos = new ArrayList<Contato>();

		while (rs.next()) {

			Contato contato = new Contato();

			contato.setId(rs.getLong("id"));
			contato.setNome(rs.getString("nome"));
			contato.setEmail(rs.getString("email"));
			contatos.add(contato);

		}

		rs.close();
		stmt.close();

		return contatos;

	}
}

struts-config.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<struts-config>

		<form-beans>
			<form-bean
				name="ContatoForm"
				type="br.com.thiago.struts.form.ContatoForm"/>
		</form-beans>

	<action-mappings>
		
		<action
			path="/teste"
			type="br.com.thiago.struts.action.TesteSimplesAction">
			<forward name="ok" path="/exemplo.jsp"/>
		</action>
		
		<action
			path="/listacontatos"
			type="br.com.thiago.struts.action.ListaContatosAction">
			<forward name="lista" path="/lista.jsp"/>
			<forward name="vazia" path="/vazia.jsp"/>
		</action>
		
		<action  
			path="/novoContato"  
			type="br.com.thiago.struts.action.AdicionaContatoAction"  
			name="ContatoForm"  
			scope="request"  
			validate="true"  
			input="/novo.jsp">  
			<forward name="lista" path="/lista.jsp"/>
			<forward name="vazia" path="/vazia.jsp"/>  
		</action>
		
		<action
			path="/removeContato"
			type="br.com.thiago.struts.action.RemoveContatoAction"
			name="RemoveContatoForm"
			scope="request"
			validade="true">
			<forward name="remove" path="lista.jsp"/>
		</action>
				
	</action-mappings>
	
	<!-- Arquivo de Mensagens -->
	<message-resources parameter="MessageResources"/>
	
</struts-config>

Erro

HTTP Status 500 -

type Exception report

message

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

exception

javax.servlet.ServletException: java.lang.NullPointerException
	org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:286)
	org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
	org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

root cause

java.lang.NullPointerException
	br.com.thiago.struts.action.RemoveContatoAction.execute(RemoveContatoAction.java:24)
	org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
	org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
	org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
	org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
	org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304)
	org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
	org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
	org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
	org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

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

6 Respostas

robinsonbsilva

jovem, debugue essa linha:

Action RemoverContato

Line 24: Contato contato = ((RemoveContatoForm) form).getContato();

Provalvelmente você está dando um cast em NULL.

T

E ai Robson,

Cara, debuguei e ele tá trazendo o form como null…

Contato contato = ((RemoveContatoForm) formb[/b]).getContato();

O que eu posso fazer?

R

Tandrade,

vc não mapeou o form RemoveContatoForm no struts-config.xml .

Att

T

Rachel Vital:
Tandrade,

vc não mapeou o form RemoveContatoForm no struts-config.xml .

Att

Opa, mapeei sim cara…

<action
			path="/removeContato"
			type="br.com.thiago.struts.action.RemoveContatoAction"
			name="RemoveContatoForm"
			scope="request"
			validade="true">
			<forward name="remove" path="lista.jsp"/>
		</action>
R

tandrade86:
Rachel Vital:
Tandrade,

vc não mapeou o form RemoveContatoForm no struts-config.xml .

Att

Opa, mapeei sim cara…

<action path="/removeContato" type="br.com.thiago.struts.action.RemoveContatoAction" name="RemoveContatoForm" scope="request" validade="true"> <forward name="remove" path="lista.jsp"/> </action>

Opa Cara! Esse mapeamento é do action … mas cadê o do form ??? Vc só mapeou o form ContatoForm no struts-config.xml

<form-beans> <form-bean name="ContatoForm" type="br.com.thiago.struts.form.ContatoForm"/> </form-beans>

Seus forms beans tem q está mapeado <form-bean … bla bla

T

Rachel Vital:
tandrade86:
Rachel Vital:
Tandrade,

vc não mapeou o form RemoveContatoForm no struts-config.xml .

Att

Opa, mapeei sim cara…

<action path="/removeContato" type="br.com.thiago.struts.action.RemoveContatoAction" name="RemoveContatoForm" scope="request" validade="true"> <forward name="remove" path="lista.jsp"/> </action>

Opa Cara! Esse mapeamento é do action … mas cadê o do form ??? Vc só mapeou o form ContatoForm no struts-config.xml

<form-beans> <form-bean name="ContatoForm" type="br.com.thiago.struts.form.ContatoForm"/> </form-beans>

Seus forms beans tem q está mapeado <form-bean … bla bla

Puta bola fora minha hein… kkkkkkkkkkk

vlw Rachel… abraços

Criado 18 de julho de 2008
Ultima resposta 18 de jul. de 2008
Respostas 6
Participantes 3