Aprendendo Servlet

Minha servlet não da nenhum erro, simplesmente não inseri o registro do BD

Alguem pode ver c eu escrevi certo???

Se alguem tiver um exemplo de servlet inserindo registro vindo do jsp agradeço…

Abraçossss
[b]

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


			String nome =  request.getParameter("nome");
			String email = request.getParameter("email");
			String endereco = request.getParameter("endereco");
			
			Contato contato = new Contato();
			contato.setNome(nome);
			contato.setEmail(email);
			contato.setEndereco(endereco);
			
			
				try {
					
					ContatoDAO dao = new ContatoDAO();	
					dao.adiciona(contato);
					
				} catch (SQLException e) {
					throw new ServletException(e);
					
				}[/b]

O que o metodo adiciona() faz?

Ele insere no banco olha :

public void adiciona(Contato contato) throws SQLException {

	// prepared Statement pra inserção
	PreparedStatement stmt = this.connection.prepareStatement("INSERT " +
			"INTO " +
			"contatos (nome, " +
			"email, " +
			"endereco) " +
			"VALUES " +
			"(?,?,?)");
	//seta os valores
	stmt.setString(1, contato.getNome());
	stmt.setString(2, contato.getEmail());
	stmt.setString(3, contato.getEndereco());
	
	//execute
	stmt.execute();
	stmt.close();
	
	

}

O seu formulário está enviando os dados via GET mesmo? :slight_smile:

Se o ambiente que estiver usando permitir, poderia tentar usar o debugador para confirmar que o metodo adiciona estah sendo chamado e se os parametros estao sendo passados corretamente.

Em ultimo caso, voce pode tentar colocar uns System.out.println() em pontos estrategicos e verificar isso na mao. :smiley:

Dica: use executeUpdate() no lugar de execute(). Ele retorna o numeros de linhas alteradas (atualizadas, inseridas ou apagadas), isso facilita na hora de debugar a aplicacao.

Esta usando POST no Form, então mudei minha servlet
para post tambem

Ficou assim :

package br.com.caelum.servlet;

import java.io.*;
import java.sql.SQLException;

import javax.servlet.;
import javax.servlet.http.
;

import br.com.caelum.jdbc.dao.ContatoDAO;
import br.com.caelum.jdbc.modelo.Contato;

public class teste extends javax.servlet.http.HttpServlet {

/**
 * 
 */
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		 
	}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String nome =  request.getParameter("nome");
	String email = request.getParameter("email");
	String endereco = request.getParameter("endereco");
	
	Contato contato = new Contato();
	contato.setNome(nome);
	contato.setEmail(email);
	contato.setEndereco(endereco);
	
	
		try {
			
			ContatoDAO dao = new ContatoDAO();	
			dao.adiciona(contato);
			
		} catch (SQLException e) {
			throw new ServletException(e);
			
		}
}

}

e O Erro foi esse :

HTTP Status 404 - /treinamento/teste


type Status report

message /treinamento/teste

description The requested resource (/treinamento/teste) is not available.


Apache Tomcat/5.5.12

Alguem sabe o que pode ser???

Cara…isso ai é erro de mapeamento no seu web.xml,

cola ele ai e a ação que é chamada na sua tela pra vermos onde exatamente está o erro vlw? :wink:

[quote=legionarioba]Cara…isso ai é erro de mapeamento no seu web.xml,

cola ele ai e a ação que é chamada na sua tela pra vermos onde exatamente está o erro vlw? ;)[/quote]

meu web.xml

<?xml version=“1.0” encoding=“UTF-8”?>
<web-app id=“WebApp_ID” version=“2.4” xmlns=“http://java.sun.com/xml/ns/j2ee” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=“http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>
<display-name>
treinamento</display-name>
<servlet>
<description>
</description>
<display-name>
OlaMundo</display-name>
<servlet-name>OlaMundo</servlet-name>
<servlet-class>
br.com.caelum.servlet.OlaMundo</servlet-class>
</servlet>

&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;OlaMundo&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/OlaMundo&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;

&lt;servlet&gt;
	&lt;description&gt;
	&lt;/description&gt;
	&lt;display-name&gt;
	TestaParametros&lt;/display-name&gt;
	&lt;servlet-name&gt;TestaParametros&lt;/servlet-name&gt;
	&lt;servlet-class&gt;
	br.com.caelum.servlet.TestaParametros&lt;/servlet-class&gt;
&lt;/servlet&gt;
&lt;servlet&gt;
	&lt;description&gt;
	&lt;/description&gt;
	&lt;display-name&gt;
	TestaErro&lt;/display-name&gt;
	&lt;servlet-name&gt;TestaErro&lt;/servlet-name&gt;
	&lt;servlet-class&gt;
	br.com.caelum.servlet.TestaErro&lt;/servlet-class&gt;
&lt;/servlet&gt;
&lt;servlet&gt;
	&lt;description&gt;
	&lt;/description&gt;
	&lt;display-name&gt;
	AdicionaContato&lt;/display-name&gt;
	&lt;servlet-name&gt;AdicionaContato&lt;/servlet-name&gt;
	&lt;servlet-class&gt;
	br.com.caelum.servlet.AdicionaContato&lt;/servlet-class&gt;
&lt;/servlet&gt;
&lt;servlet&gt;
	&lt;description&gt;
	&lt;/description&gt;
	&lt;display-name&gt;
	ADD&lt;/display-name&gt;
	&lt;servlet-name&gt;ADD&lt;/servlet-name&gt;
	&lt;servlet-class&gt;
	br.com.caelum.servlet.ADD&lt;/servlet-class&gt;
&lt;/servlet&gt;
&lt;servlet&gt;
	&lt;description&gt;
	&lt;/description&gt;
	&lt;display-name&gt;
	teste&lt;/display-name&gt;
	&lt;servlet-name&gt;teste&lt;/servlet-name&gt;
	&lt;servlet-class&gt;
	br.com.caelum.servlet.teste&lt;/servlet-class&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;TestaParametros&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/TestaParametros&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;TestaErro&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/TestaErro&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;AdicionaContato&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/AdicionaContato&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;ADD&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/ADD&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;teste&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/teste.java&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;

&lt;welcome-file-list&gt;
	&lt;welcome-file&gt;index.html&lt;/welcome-file&gt;
	&lt;welcome-file&gt;index.htm&lt;/welcome-file&gt;
	&lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
	&lt;welcome-file&gt;default.html&lt;/welcome-file&gt;
	&lt;welcome-file&gt;default.htm&lt;/welcome-file&gt;
	&lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt;
&lt;/welcome-file-list&gt;

</web-app>

chamada do post

<%@ page language=“java” contentType=“text/html; charset=ISO-8859-1”
pageEncoding=“ISO-8859-1”%>
<!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>Insert title here</title>
</head>
<body>
<form action=“teste.java” method=“post”>
<input type=“text” name=“nome” value=""/>
<input type=“text” name=“email” value=""/>
<input type=“text” name=“endereco” value=""/>
<input type=“submit” value=“Enviar”/>

</form>
</body>
</html>

HTTP Status 404 - Servlet teste is not available


type Status report

message Servlet teste is not available

description The requested resource (Servlet teste is not available) is not available.


Apache Tomcat/5.5.12

[b}Para testar criei uma nova servlet :{/b}

package br.com.caelum.servlet;

import java.io.IOException;
import java.sql.SQLException;

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

import br.com.caelum.jdbc.dao.ContatoDAO;
import br.com.caelum.jdbc.modelo.Contato;

/**

  • Servlet implementation class for Servlet: teste4

/
public class teste4 extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
/
*
*
*/
private static final long serialVersionUID = 1L;

/* (non-Java-doc)
 * @see javax.servlet.http.HttpServlet#HttpServlet()
 */
public teste4() {
	super();
}   	

/* (non-Java-doc)
 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	// TODO Auto-generated method stub
}  	

/* (non-Java-doc)
 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	String nome =  request.getParameter("nome");
	String email = request.getParameter("email");
	String endereco = request.getParameter("endereco");
	
	Contato contato = new Contato();
	contato.setNome(nome);
	contato.setEmail(email);
	contato.setEndereco(endereco);
	
	
		try {
			
			ContatoDAO dao = new ContatoDAO();	
			dao.adiciona(contato);
			
		} catch (SQLException e) {
			throw new ServletException(e);
			
		}
}   	  	    

}

AGORA O ERRO É DIFERENTE :

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: Servlet execution threw an exception

root cause

java.lang.NoClassDefFoundError: br/com/caelum/jdbc/dao/ContatoDAO
br.com.caelum.servlet.teste4.doPost(teste4.java:54)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

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