| Autor |
Mensagem |
![[Post New]](/templates/default/images/icon_minipost_new.gif) 03/02/2012 21:18:23
|
thiserver
HelloWorld
Membro desde: 26/01/2012 12:55:26
Mensagens: 13
Offline
|
eu nao sei o erro alguem pode me ajudar
package br.com.modelo;
public class Pessoa {
public long id;
public String nome;
public String endereco;
public String email;
public String telefone;
public String celular;
public String cidade;
public String estado;
public String senha;
public void setId(long l) {
this.id = l;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getCelular() {
return celular;
}
public void setCelular(String celular) {
this.celular = celular;
}
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 getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getId() {
return null;
}
}
package br.com.infra;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionFactory {
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost/CadastroFisico", "root", "people");
} catch (SQLException e) {
throw new RuntimeException(e);
}catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
package br.com.infra;
import java.sql.SQLException;
import java.util.List;
public interface DAO<T> {
public void adiciona(T entidade) throws SQLException;
public void altera(T entidade) throws SQLException;
public void deleta(T entidade) throws SQLException;
public T lista(String pesquisa) throws SQLException;
public List<T> listaTudo() throws SQLException;
}
package br.com.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.infra.ConnectionFactory;
import br.com.infra.DAO;
import br.com.modelo.Pessoa;
public class PessoaDAO implements DAO<Pessoa> {
// a conexao com o banco de dados
private Connection con;
public PessoaDAO() {
this.con = new ConnectionFactory().getConnection();
}
@Override
public void adiciona(Pessoa entidade) throws SQLException {
String sql = "insert into pessoa (nome,endereco,email,telefone,celular,cidade,estado,senha) values (?,?,?,?,?,?,?,?)";
PreparedStatement stmt = null;
try {
stmt = (PreparedStatement) con.prepareStatement(sql);
stmt.setString(1, entidade.getNome());
stmt.setString(2, entidade.getEndereco());
stmt.setString(3, entidade.getEmail());
stmt.setString(4, entidade.getTelefone());
stmt.setString(5, entidade.getCelular());
stmt.setString(6, entidade.getCidade());
stmt.setString(7, entidade.getEstado());
stmt.setString(8, entidade.getSenha());
stmt.execute();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
con.close();
stmt.close();
}
}
@Override
public void altera(Pessoa entidade) throws SQLException {
String sql = "update pessoa set ";
int t = 0;
int count = 1;
if (entidade.getNome() != null && !entidade.getNome().equals("")) {
if (t == 1) {
sql = sql + ",";
}
sql = sql + "nome=?";
t = 1;
}
if (entidade.getEndereco() != null && !entidade.getEndereco().equals("")) {
if (t == 1) {
sql = sql + ", ";
}
sql = sql + "endereco=?";
t = 1;
}
if (entidade.getEmail() != null && !entidade.getEmail().equals("")) {
if (t == 1) {
sql = sql + ", ";
}
sql = sql + "email=?";
t = 1;
}
if (entidade.getTelefone() != null && !entidade.getTelefone().equals("")) {
if(t == 1){
sql = sql + ",";
}
sql = sql + "telefone=?";
t =1;
}
if (entidade.getCelular() != null && !entidade.getCelular().equals("")) {
if(t == 1){
sql = sql + ",";
}
sql = sql + "celular=?";
t =1;
}
if (entidade.getCidade() != null && !entidade.getCidade().equals("")) {
if(t == 1){
sql = sql + ",";
}
sql = sql + "cidade=?";
t =1;
}
if (entidade.getEstado() != null && !entidade.getEstado().equals("")) {
if(t == 1){
sql = sql + ",";
}
sql = sql + "estado=?";
t =1;
}
if (entidade.getSenha() != null && !entidade.getSenha().equals("")) {
if (t == 1) {
sql = sql + ", ";
}
sql = sql + "senha=?";
t = 1;
}
sql = sql + " where id= ? ";
PreparedStatement stmt = null;
try {
stmt = (PreparedStatement) con.prepareStatement(sql);
if (entidade.getNome() != null && !entidade.getNome().equals("")) {
stmt.setString(count, entidade.getNome());
count++;
}
if (entidade.getEndereco() != null && !entidade.getEndereco().equals("")) {
stmt.setString(count, entidade.getEndereco());
count++;
}
if (entidade.getEmail() != null && !entidade.getEmail().equals("")) {
stmt.setString(count, entidade.getEmail());
count++;
}
if (entidade.getTelefone() != null && !entidade.getTelefone().equals("")) {
stmt.setString(count, entidade.getTelefone());
count++;
}
if (entidade.getCelular() != null && !entidade.getCelular().equals("")) {
stmt.setString(count, entidade.getCelular());
count++;
}
if (entidade.getCidade() != null && !entidade.getCidade().equals("")) {
stmt.setString(count, entidade.getCidade());
count++;
}
if (entidade.getEstado() != null && !entidade.getEstado().equals("")) {
stmt.setString(count, entidade.getEstado());
count++;
}
if (entidade.getSenha() != null && !entidade.getSenha().equals("")) {
stmt.setString(count, entidade.getSenha());
count++;
}
stmt.setString(count, entidade.getId());
stmt.execute();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
con.close();
stmt.close();
}
}
@Override
public void deleta(Pessoa entidade) throws SQLException {
PreparedStatement stmt = null;
try {
stmt = (PreparedStatement) con.prepareStatement("delete from pessoa where id=?");
stmt.setString(1, entidade.getId());
stmt.execute();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
con.close();
stmt.close();
}
}
@Override
public Pessoa lista(String pesquisa) throws SQLException {
Pessoa entidade = new Pessoa();
String sql = "select * from pessoa where id = ?";
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = (PreparedStatement) con.prepareStatement(sql);
stmt.setLong(1, new Long(pesquisa));
rs = stmt.executeQuery();
if (rs.next()) {
entidade.setNome(rs.getString("nome"));
entidade.setEndereco(rs.getString("endereco"));
entidade.setEmail(rs.getString("email"));
entidade.setTelefone(rs.getString("telefone"));
entidade.setCelular(rs.getString("celular"));
entidade.setCidade(rs.getString("cidade"));
entidade.setEstado(rs.getString("estado"));
entidade.setSenha(rs.getString("senha"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
stmt.close();
rs.close();
con.close();
}
return entidade;
}
@Override
public List<Pessoa> listaTudo() throws SQLException {
List<Pessoa> pessoas = new ArrayList<Pessoa>();
String sql = "select * from pessoa ";
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = (PreparedStatement) con.prepareStatement(sql);
rs = stmt.executeQuery();
Pessoa entidade = null;
while (rs.next()) {
entidade = new Pessoa();
entidade.setNome(rs.getString("nome"));
entidade.setEndereco(rs.getString("endereco"));
entidade.setEmail(rs.getString("email"));
entidade.setTelefone(rs.getString("telefone"));
entidade.setCelular(rs.getString("celular"));
entidade.setCidade(rs.getString("cidade"));
entidade.setEstado(rs.getString("estado"));
entidade.setSenha(rs.getString("senha"));
pessoas.add(entidade);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
stmt.close();
rs.close();
con.close();
}
return pessoas;
}
}
package br.com.controle;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.dao.PessoaDAO;
import br.com.modelo.Pessoa;
@WebServlet("/pessoa")
public class PessoaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public PessoaServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String usuario = request.getParameter("usuario");
String senha = request.getParameter("senha");
PrintWriter printWriter = response.getWriter();
recebiFormulario(usuario, senha, printWriter);
}
private void recebiFormulario(String usuario,String senha,PrintWriter printWriter){
PrintWriter saida = printWriter;
saida.print("<h2>ola mundo<h2>");
saida.print("<P>ola mundo</P>");
saida.print("<P>usuario:" + usuario +"</P>");
saida.print("<P>senha:" + senha +"</P>");
saida.print("<a href=\"/pessoa\">inicio</a>");
saida.print("</body></html>");
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// busca o writer
PrintWriter out = response.getWriter();
PessoaDAO dao = new PessoaDAO();
String action = request.getParameter("action");
if (action != null && action.equals("gravar")) {
// buscando os parâmetros no request
Integer id = 0;
if (request.getParameter("id") != null && !request.getParameter("id").equals("")) {
id = Integer.parseInt(request.getParameter("id"));
}
String nome = request.getParameter("nome");
String endereco = request.getParameter("endereco");
String email = request.getParameter("email");
String telefone = request.getParameter("telefone");
String celular = request.getParameter("celular");
String cidade = request.getParameter("cidade");
String estado = request.getParameter("estado");
String senha = request.getParameter("senha");
Pessoa pessoa = new Pessoa();
pessoa.setNome(nome);
pessoa.setEndereco(endereco);
pessoa.setEmail(email);
pessoa.setTelefone(telefone);
pessoa.setCelular(celular);
pessoa.setCidade(cidade);
pessoa.setEstado(estado);
pessoa.setSenha(senha);
try {
if (id != null && id > 0) {
pessoa.setId(new Long(id));
dao.altera(pessoa);
} else {
dao.adiciona(pessoa);
}
RequestDispatcher dispatcher = request.getRequestDispatcher("pessoa.jsp");
dispatcher.forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (action != null && action.equals("excluir")) {
Integer id = 0;
if (request.getParameter("id") != null && !request.getParameter("id").equals("")) {
id = Integer.parseInt(request.getParameter("id"));
}
Pessoa pessoa = new Pessoa();
pessoa.setId(new Long(id));
try {
dao.deleta(pessoa);
RequestDispatcher dispatcher = request.getRequestDispatcher("pessoa.jsp");
dispatcher.forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
RequestDispatcher dispatcher = request.getRequestDispatcher("pessoa.jsp");
dispatcher.forward(request, response);
}
}
}
o erro é este
HTTP Status 500 -
Tipo de relatório de exceção
mensagem
Descrição O servidor encontrou um erro interno () que o impediu de cumprir este pedido.
exceção
java.lang.RuntimeException: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 'Estado' Coluna não pode ser nulo
br.com.dao.PessoaDAO.adiciona (PessoaDAO.java: 42)
br.com.controle.PessoaServlet.service (PessoaServlet.java: 8
javax.servlet.http.HttpServlet.service (HttpServlet.java: 722)
causa raiz
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 'Estado' Coluna não pode ser nulo
sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance (Origem Desconhecida)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance (Origem Desconhecida)
java.lang.reflect.Constructor.newInstance (Origem Desconhecida)
com.mysql.jdbc.Util.handleNewInstance (Util.java: 411)
com.mysql.jdbc.Util.getInstance (Util.java: 386)
com.mysql.jdbc.SQLError.createSQLException (SQLError.java: 1039)
com.mysql.jdbc.MysqlIO.checkErrorPacket (MysqlIO.java: 3597)
com.mysql.jdbc.MysqlIO.checkErrorPacket (MysqlIO.java: 3529)
com.mysql.jdbc.MysqlIO.sendCommand (MysqlIO.java: 1990)
com.mysql.jdbc.MysqlIO.sqlQueryDirect (MysqlIO.java: 2151)
com.mysql.jdbc.ConnectionImpl.execSQL (ConnectionImpl.java: 2625)
com.mysql.jdbc.PreparedStatement.executeInternal (PreparedStatement.java: 2119)
com.mysql.jdbc.PreparedStatement.execute (PreparedStatement.java: 1362)
br.com.dao.PessoaDAO.adiciona (PessoaDAO.java: 39)
br.com.controle.PessoaServlet.service (PessoaServlet.java: 8
javax.servlet.http.HttpServlet.service (HttpServlet.java: 722)
note A pilha completa da causa raiz disponível nos logs do Apache Tomcat/7.0.23.
Apache Tomcat/7.0.23
|
|
|
 |
|
|
![[Post New]](/templates/default/images/icon_minipost_new.gif) 03/02/2012 21:28:07
|
Fexx
Java Ninja
![[Avatar]](/images/avatar/8606e546e761dbb7e76dcb20745ec9d4.jpg)
Membro desde: 22/06/2011 07:29:26
Mensagens: 273
Localização: São Paulo - SP
Offline
|
Utilize as tags code [ code] para postra codigos.
Mas o proprio erro te disse o que está errado, veja: 'Estado' Coluna não pode ser nulo.
Ou seja, vc está passando valores nulo para um campo no banco onde não aceita nulo
|
" Se diante de mim não se abrir o mar, Deus vai me fazer andar por sobre as águas" |
|
|
 |
![[Post New]](/templates/default/images/icon_minipost_new.gif) 03/02/2012 21:30:38
|
Roger75
GUJ Master
![[Avatar]](/images/avatar/a82d922b133be19c1171534e6594f754.jpg)
Membro desde: 26/10/2003 12:18:59
Mensagens: 1294
Online
|
Bem, pelo que o stacktrace diz, você deve estar passando null ou branco no campo Estado. Aconselho debugar no Eclipse, para descobrir em que ponto isso ocorre.
|
|
|
 |
![[Post New]](/templates/default/images/icon_minipost_new.gif) 05/02/2012 09:14:48
|
LPJava
GUJ Hacker
Membro desde: 18/04/2006 12:50:23
Mensagens: 5524
Localização: Bahia/Porto Alegre
Offline
|
http://www.guj.com.br/java/50115-voce-e-novo-no-guj-vai-criar-um-topico-e-colar-seu-codigo-fonte-leia-aqui-antes-por-favor
dar uma olhada, por favor.
|
Sun Certified Java Programmer 5.0
Blog:http://www.camilolopes.com
Twitter:www.twitter.com/camilolope
Linkedin: http://br.linkedin.com/in/camilolopes
Curso online OCPJP: http://pro.imasters.com.br/online/cursos/preparatorio-para-certificacao-java-ocjp
Autor livro Guia SCJP & JEE c/ Frameworks: http://blog.camilolopes.com.br/livrosrevistaspalestras/
|
|
|
 |
|
|
|
|