簡體   English   中英

帶有數據庫和錯誤的Servlet中的Java Mail API為NullPointerException

[英]Java Mail API in Servlet with database and error is NullPointerException

我正在從數據庫中向注冊學生發送電子郵件,並獲取用戶的電子郵件地址。 並檢查數據庫中的電子郵件,我正在使用smtp服務器向用戶發送有關其prn(即ID)和密碼的電子郵件。 我有1個servlet和一個模型類以及1個jsp。 我已經附上了代碼的屏幕截圖。 謝謝,請稍作解決。幫助。 我是學生。 提前致謝。 :)我只收到1個錯誤,即NullPointerException

package com.student.connection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Transport;
import javax.activation.*;

public class Mailer {

private Connection conn = null;
private PreparedStatement ps = null;
private Statement stmt = null;
private ResultSet rs = null;

public void send(String emailaddress) throws SQLException, ClassNotFoundException {
    int prn = 0;
    final String username = "12030142084@sicsr.ac.in";
    final String password = "mypassword";
    String email = new String();
    String pass = new String();

    System.out.println("Test");
    String query = "select prn,email,password from studentdetails where email=" + emailaddress;

    conn = DBConnection.createDBConnection();
    stmt = conn.createStatement();
    rs = stmt.executeQuery(query);

    while (rs.next()) {
        prn = rs.getInt(1);
        email = rs.getString("email");
        pass = rs.getString("password");
    }

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
    try {

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("12030142084@sicsr.ac.in"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(email));
        message.setSubject("Password Recover");
        message.setText("Your Prn is " + prn + "You Password is " + pass);

        Transport.send(message);

        System.out.println("Email Sent Succsessfully");

    } catch (MessagingException e) {
        //throw new RuntimeException(e);
    } finally {
        conn.close();
    }
}

}


package com.student.controller;

public class ContactServlet extends HttpServlet {

private Mailer mailer;

@Override
public void init() {
    String hostname = "smtp.gmail.com";
    int port = 587;
    String username = "12030142084@sicsr.ac.in";
    String password = "mypassword";

}

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        /* TODO output your page here. You may use following sample code. */
        String emailaddress = request.getParameter("emailadd");
        // Do some validations and then send mail:

        String msg = "";
        try {
            msg = "Mail Successfully Sent!!";
            System.out.println("Check");

            mailer.send("emailaddress"); // here is the error
            System.out.println("Check2");

            request.setAttribute("message", "Mail succesfully sent!");
            request.getRequestDispatcher("/WEB-INF/recoverpassword.jsp").forward(request, response);
            response.sendRedirect("index.jsp?error=" + msg);
        } catch (Exception e) {
            response.sendRedirect("recoverpassword.jsp" + msg);
            throw new ServletException("Mailer failed", e);
        }
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet ContactServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet ContactServlet at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    } finally {
        out.close();
    }
}


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    processRequest(request, response);
}


@Override
public String getServletInfo() {
    return "Short description";
}

}


WARNING: StandardWrapperValve[ContactServlet]: PWC1406: Servlet.service() for servlet ContactServlet threw exception java.lang.NullPointerException
at com.student.controller.ContactServlet.processRequest(ContactServlet.java:50)
at com.student.controller.ContactServlet.doPost(ContactServlet.java:102)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)

Jsp文件是正確的,它只需要一個用戶輸入,並且標識為emailadd

有人請幫忙。

那是因為mailer尚未初始化。

private Mailer mailer; // you're just declaring mailer
...
mailer.send("emailaddress"); // without initialization you're trying to call a method on it.

在您的init()方法中,您需要執行以下操作:

mailer = new Mailer(); // just an example. But you need to initialize your mailer.
        mailer.send("emailaddress"); // here is the error

將導致NullPointerException,因為在servlet代碼中沒有初始化mailer 郵件對象被初始化為null,對其調用任何方法都將導致NPE。 確保在調用send或其中的任何其他方法之前先對其進行初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM