【问题标题】:I received Error java.lang.NullPointerException我收到错误 java.lang.NullPointerException
【发布时间】:2013-06-30 07:47:41
【问题描述】:

我的代码有问题:现在我使用 Stringbuilder 连接日期,但收到一些错误: 我的 Servlet:

  package br.com.cad.basica;

import java.util.Calendar;

public class Contato {

        private Long id;
        private String nome;
        private String sobrenome;
        private String email;
        private String endereco;
        private Calendar dataNascimento1;
        private Calendar dataNascimento2;
        private Calendar dataNascimento3;
        private String rg;
        private String cpf;
        private String sexo;
        public Long getId() {
            return id;
        }
        public void setId(Long id) {
            this.id = id;
        }
        public String getNome() {
            return nome;
        }
        public void setNome(String nome) {
            this.nome = nome;
        }
        public String getSobrenome() {
            return sobrenome;
        }
        public void setSobrenome(String sobrenome) {
            this.sobrenome = sobrenome;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public String getEndereco() {
            return endereco;
        }
        public void setEndereco(String endereco) {
            this.endereco = endereco;
        }
        public Calendar getDataNascimento1() {
            return dataNascimento1;
        }
        public void setDataNascimento1(Calendar dataNascimento1) {
            this.dataNascimento1 = dataNascimento1;
        }
        public Calendar getDataNascimento2() {
            return dataNascimento2;
        }
        public void setDataNascimento2(Calendar dataNascimento2) {
            this.dataNascimento2 = dataNascimento2;
        }
        public Calendar getDataNascimento3() {
            return dataNascimento3;
        }
        public void setDataNascimento3(Calendar dataNascimento3) {
            this.dataNascimento3 = dataNascimento3;
        }
        public String getRg() {
            return rg;
        }
        public void setRg(String rg) {
            this.rg = rg;
        }
        public String getCpf() {
            return cpf;
        }
        public void setCpf(String cpf) {
            this.cpf = cpf;
        }
        public String getSexo() {
            return sexo;
        }
        public void setSexo(String sexo) {
            this.sexo = sexo;
        }




}

我的班级Contato(我不知道是否需要在这里实现一些代码?)

  package br.com.cad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.cad.dao.Cadastro;
import br.com.cad.basica.Contato;

public class AddDados extends HttpServlet{

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


 PrintWriter out = response.getWriter();
     String nome = request.getParameter("nome");
     String sobrenome = request.getParameter("sobrenome");
     String rg = request.getParameter("rg");  
     String cpf = request.getParameter("cpf");  
     String sexo = request.getParameter("sexo");
     StringBuilder finalDate = new StringBuilder("DataNascimento1")
.append("/"+request.getParameter("DataNascimento‌​2"))
.append("/"+request.getParameter("DataNascimento3"));

 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
 finalDate.toString(); 
 Contato contato = new Contato();  
     contato.setNome(nome); 
     contato.setSobrenome(sobrenome);
     contato.setRg(rg);  
     contato.setCpf(cpf);  
     contato.setSexo(sexo);
        if ("Masculino".equals(contato.getSexo())) {  
         contato.setSexo("M");  
            } else {  
         contato.setSexo("F");  
        }  

 Cadastro dao = new Cadastro();  
     dao.adiciona(contato);
 out.println("<html>");  
 out.println("<body>");  
 out.println("Contato " + contato.getNome() + " adicionado com sucesso");  
 out.println("</body>");  
 out.println("</html>"); 

} 
}  

我的对象道:

 package br.com.cad.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Date;

import br.com.cad.dao.ConnectDb;
import br.com.cad.basica.Contato;
public class Cadastro {  

    private Connection connection;  


    public Cadastro() {  
        this.connection = new ConnectDb().getConnection();  
    }  

    public void adiciona(Contato contato) {  
        String sql = "INSERT INTO dados_cadastro(pf_nome, pf_ultimonome, pf_rg, pf_cpf, pf_sexo,pf_dt_nasc) VALUES(?,?,?,?,?,?,?,?)";  
        try {  

            PreparedStatement stmt = connection.prepareStatement(sql);  

            stmt.setString(1, contato.getNome());  
            stmt.setString(2, contato.getSobrenome());
            stmt.setString(3, contato.getRg());  
            stmt.setString(4, contato.getCpf());
            stmt.setString(5, contato.getSexo());
            stmt.setDate(6, new Date( contato.getDataNascimento1().getTimeInMillis()) );


            stmt.execute();  
            stmt.close();  
            System.out.println("Cadastro realizado com sucesso!.");  
        } catch(SQLException sqlException) {  
            throw new RuntimeException(sqlException);  
        }  
    }  
}

我的 htmllet 代码 cadastra.jsp(将数据发送到我的 servlet 并保存我的数据库):

<...some code here
    <label>Data de nascimento</label>  
            <br>  
                <select id="birthDay" name="dataNascimento1">  
                    <option selected="" value="">Dia</option>  
                        <option value="01">1</option>  
                        <option value="02">2</option>  
</select>  
              <select id="birthMonth" name="dataNascimento2">  
                    <option selected="" value="">Mês</option>  
                        <option value="01">janeiro</option>  
                        <option value="02">fevereiro</option>  
</select>  
              <select id="birthYear" name="dataNascimento3">  
                 <option selected="" value="">Ano</option>  
                        <option value="2013">2013</option>  
                        <option value="2012">2012</option>  
</select> 

按下提交按钮时我收到此错误:

HTTP Status 500 -

type Exception report

message

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

exception

java.lang.NullPointerException
    br.com.cad.dao.Cadastro.adiciona(Cadastro.java:30)
    br.com.cad.servlet.AddDados.service(AddDados.java:48)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.40 logs.

【问题讨论】:

  • 堆栈跟踪非常具体:您在 Cadastro.adiciona 方法中有一个 NullPointerException,在第 30 行。这意味着,第 30 行中的变量有一个 null 值并且正在用过的。请学习阅读堆栈跟踪
  • 并尝试只发布相关代码而不是完整代码。
  • NullPointerException 似乎在你调用getDataNascimento1() 的那一行——你确定这总是返回一个非空值吗?

标签: java html servlets dao


【解决方案1】:

您必须先致电contato.setDataNascimento1(someDate),然后才能添加联系人(?)。问题在于这句话:

contato.getDataNascimento1().getTimeInMillis()

contato.getDataNascimento1() 在您执行时解析为null

计算行数,该语句位于第 30 行


加法

你应该替换这些行

private Calendar dataNascimento1;
private Calendar dataNascimento2;
private Calendar dataNascimento3;

private Date dataNascimento;

并相应地更改 getter/setter。现在您有了一个包含联系人生日的字段,您可以将其添加到插入语句中而无需进一步转换。

剩下的唯一挑战是如何根据从 ui 中捕获的值创建 Date 对象。格式化程序是一种方法。但是Date 有一些方便的构造函数来根据这些值创建日期。请注意,月份是从零开始的,iaw,一月是 0,二月是 1 等等。创建 new Date(...) 后,您可以调用 Contato 类上的相应设置器并将生日存储在 DTO 中。

【讨论】:

  • 但我怀疑只是我在我的 stringbuilder finaldate 中连接了 datanascimento1+datanascimento2+datascimento3 如何添加包含 3 个日期的 finaldate? contato.getFinalDate 不起作用所以我需要做什么?
  • 我还有一些疑问。您的“Contato”类具有三个 Calendar 字段,用于birthDate(?) 和在用户界面上您的商店日、月和年的字段(作为字符串)具有相同的名称。这不太适合。将您的 DTO 设计为具有 一个 字段作为生日并将连接的字符串 解析Date
  • @Wesley - 我在回答中添加了一些提示和建议。
  • 好!!!我替换了我的课程 Contato:private Date dataNascimento;public Date getDataNascimento() { return dataNascimento; } 公共无效 setDataNascimento(日期 dataNascimento) { this.dataNascimento = dataNascimento;但我现在的疑问是如何实现我的 servlet?StringBuilder finalDate = new StringBuilder("DataNascimento1") .append("/"+request.getParameter("DataNascimento‌​2")) .append("/"+request.getParameter ("DataNascimento3")); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); finalDate.toString();这段代码我需要替换吗??
  • 用户 Integer.parseInt(someString) 将字符串转换为数字,然后查看 Date 类构造函数。最后的步骤真的不难。
猜你喜欢
  • 2017-01-05
  • 2015-01-30
  • 1970-01-01
  • 2012-03-05
  • 2014-12-15
  • 1970-01-01
  • 2022-07-27
  • 1970-01-01
  • 2013-12-19
相关资源
最近更新 更多