Got a NullPointerException in Servlet [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
*Well I have created a basic servlet program Where if user give their USN number correct it will fetch data from database else it will redirect to error.html
Whenever I Enter USN number it shows NullPointerException .Since I am using Eclipse There was No sign of error.
Note:I have Also Created a html file to enter the USN Number.
Code:
package com.abc.error;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetResult extends HttpServlet {
/**
*
*/
static final long serialVersionUID = 1L;
Connection con= null;
PreparedStatement pstmt=null;
ResultSet res=null;
public void init(){
try {
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#//localhost:1521/XE","system","system");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
#Override
public void service(HttpServletRequest request, HttpServletResponse response) {
try
{
pstmt = con.prepareStatement("SELECT * FROM VTURESULT_AUG WHERE USN =?");
String key = request.getParameter("USN");
if(key.length()!=12){
response.sendRedirect("/ServletWithError/error.html");
}
else
{
pstmt.setString(1,key);
res =pstmt.executeQuery();
if(res.next())
{
String usn = res.getString(1);
String name = res.getString(2);
int m1 = res.getInt(3);
int m2 = res.getInt(4);
int m3 = res.getInt(5);
PrintWriter pw =response.getWriter();
pw.println(usn+" "+name+" "+m1+" "+m2+" "+m3);
}
}
}
catch(SQLException | IOException e)
{
e.printStackTrace();
}
}
}
Output:
java.lang.NullPointerException
com.abc.error.GetResult.service(GetResult.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

The stacktrace says the NPE is at this line if the posted code's line numbers match your actual code:
pstmt.setString(1,key);
You can verify this by setting a breakpoint on that line.
I can't see your actual code, so there are a couple of things you should check using more breakpoints:
Is con null? If so, your init() method may not be getting called, or it's throwing an exception higher up in your log that you're not seeing.
Move your PreparedStatement declaration down to where it's being used - declaring it outside the function isn't helping you at all in this case:
PreparedStatement stmt = con.prepare(...);
And of course, verify that key is non-null.

Related

NullPointerException in Java Mysql querying [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm new to java programming and I'm making a project which implies the use of java and mysql and I cannot manage to fix a NullPointerException in this piece of code, can anyone help me?
here's the full code, the connection part is working fine, its tested
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import database.mainConnection;
public class userUtils extends mainConnection {
public static void main(String[] args ) throws Exception {
userLogin("mattia",hash("password");
}
/*public static Boolean registerUser(String name, String surname, String username, String email, String password, String Affiliation, String dateOfBirth) throws Exception {
Connection con = getConnection();
// 0000-00-00 format date
PreparedStatement query = con.prepareStatement("INSERT INTO users (UserID, Username, Email, Password, Name, Surname, BirthDate, Affiliation) VALUES (?,?,?,?,?,?,?,?)");
query.executeUpdate();
return false;
}*/
public static Boolean userLogin(String username, String password) throws Exception {
Boolean bool = null;
try{
Connection con = getConnection();
PreparedStatement query = con.prepareStatement("SELECT * FROM users WHERE Username=? AND Password=?");
query.setString(1, username);
query.setString(2, password);
ResultSet result = query.executeQuery();
if(result.next()) {
bool = true;
}
} catch(Exception e) {
e.printStackTrace();
}
return bool;
}
}
Also it doesn't give any results back, but i guess its due to the nullpointerexception
the error points at
con.prepareStatement("SELECT * FROM users WHERE Username=? AND Password=?"); and at a printlnine where i invoke the method
Instead of null assign false to your bool variable, try to use boolean a primitive datatype for return type of class and bool instead of wrapper class Boolean.
Boolean bool = false;
Boolean bool = null;
or
Connection con = getConnection();
should be the problem.
If the result returns nothing, bool will be null and returned by function.
And check for return of getConnection() is not null.

Error in ResultSet Object [duplicate]

This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 5 years ago.
I'm thinking about the MVC application and for that and in the loading method of the lists that can be deleted with elements that are going to be chosen to make the query.
The classes associated with this are:
package modelo;
import java.sql.*;
import controlador.*;
public class CargaMenus {
public CargaMenus() {
miconexion = new Conexion();
}
public String ejecutaConsultas() { //Va a devolver el nombre de las tareas en el conbobox
Tareas miTarea = null;
Connection accesoBBDD = miconexion.dameConexion();
try {
Statement secciones = accesoBBDD.createStatement();
Statement descripciones = accesoBBDD.createStatement();
rs = secciones.executeQuery("SELECT DISTINCTROW NOMTAREA FROM TAREAS");
rs2 = descripciones.executeQuery("SELECT DISTINCTROW DESCTAREA FROM TAREAS");
miTarea = new Tareas();
miTarea.setNomtarea(rs.getString(1));
miTarea.setDesctarea(rs2.getString(1));
rs.close();
rs2.close();
} catch (SQLException e) {
System.out.println("Error en la conexión CARGAMENUS");
e.printStackTrace();
}
return miTarea.getNomtarea();
}
public Conexion miconexion;
public ResultSet rs;
public ResultSet rs2;
private String consulta = "SELECT DISTINCTROW NOMTAREA FROM TAREAS";
private String consulta2 = "SELECT DISTINCTROW DESCTAREA FROM TAREAS";
}
and the class that executes the method and travel what is returned by the database is:
package controlador;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.ResultSet;
import modelo.CargaMenus;
import vista.Marco_Aplicacion2;
public class ControladorCargaMenus extends WindowAdapter {
public ControladorCargaMenus(Marco_Aplicacion2 elmarco) {
this.elmarco = elmarco;
}
public void windowOpened(WindowEvent e) {
obj.ejecutaConsultas();
try {
while(obj.rs.next()) {
elmarco.secciones.addItem(obj.rs.getString(1));
}
while(obj.rs2.next()) {
elmarco.paises.addItem(obj.rs2.getString(1));
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
CargaMenus obj = new CargaMenus();
private Marco_Aplicacion2 elmarco;
}
When I run the program, I only see a combobox of the 2 that I designed.
and the following error
I thought the problem would be my sql queries but I validated them and there is no problem when I run them in my mysql.
and when I only load one of the lists (the first one) commenting the lines associated with the second list, the application loads me even if it throws errors in the console
The link I'm learning about is link of tutorial
How could I do to load the lists?
You should call rs.next before getting result.
if (rs.next()) {
miTarea.setNomtarea(rs.getString(1));
miTarea.setDesctarea(rs2.getString(1));
}
The root cause is that you are not calling rs.next() before rs.getString, it is only called after the ejecutaConsultas method is run. Same applies to rs2 usage.
Also you need to follow some best practices in your code such not exposing ResultSet to outside of your class and doing proper JDBC exception handling and closing of ResultSets andConnections.

java array out of bound exception while loading text data into DataBase [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I was trying to read a text file & load into SQL Server DB but when I run the following code, I am getting Array out of bound exception.
Can one guide, how can I fix this issue?
package com.companyname.product;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoadTextFileintoDB
{
public static void main(String[] args)
{
DBase db = new DBase();
Connection conn = db.connect(
"jdbc:sqlserver://localhost\\SQLEXPRESS:1433;databaseName=ODRDev","sa","Abc-1234");
db.importData(conn,args[0]);
}
}
class DBase
{
public DBase()
{
}
public Connection connect(String db_connect_str,
String db_userid, String db_password)
{
Connection conn;
try
{
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn = DriverManager.getConnection(db_connect_str,
db_userid, db_password);
}
catch(Exception e)
{
e.printStackTrace();
conn = null;
}
return conn;
}
public void importData(Connection conn,String filename)
{
Statement stmt;
String query;
try
{
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
query = "LOAD FROM 'C:/Investedge/JH765IDG_1.txt INTO TABLE InvestedgeDaily (AccountNumber,Code,Date,value);";
stmt.executeUpdate(query);
}
catch(Exception e)
{
e.printStackTrace();
stmt = null;
}
}
};
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at
com.companyname.product.LoadTextFileintoDB.main(LoadTextFileintoDB.java:15)
This Code triggers the exception:
args[0]
Obviously, no parameters were passed to the executable when executing it.
args is an array of the parameters passed to the executable in the command line.

How do I display a web page with information from a database, from a servlet? [duplicate]

This question already exists:
I have retrieved information from a database, but how do I format it properly? Perhaps using html [duplicate]
Closed 7 years ago.
I've tried to retrieve and print the firstname, lastname and address from a database and then display it. I have the servlet below, can someone please help me, thanks :) Will I have to use html at all?
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class PersonalInfoOutput extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String address = request.getParameter("address");
boolean st = false;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps = con.prepareStatement("select FirstName, LastName, Address from payroll_system.employee_info where employeeID = 1234");
ResultSet rs = ps.executeQuery();
st = rs.next();
if(st){
out.println(firstname);
}
}catch(Exception e)
{
e.printStackTrace();
}
out.close();
}
}
The output I'm receiving is:
null
Use exceptional handling. close the out object. look the below example and try to debug more : http://www.javawebtutor.com/articles/servlets/servlet_db_example.html

Java Unreachable code error

I am creating a Java class for SmartFox Server Extension. It is trying to access MySQL Database.
I am receiving a error called Unreachable Code on the line session.setProperty("DatabaseID", dbId);
package sfs2x.extension.test.dblogin;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.smartfoxserver.bitswarm.sessions.ISession;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.db.IDBManager;
import com.smartfoxserver.v2.exceptions.SFSErrorCode;
import com.smartfoxserver.v2.exceptions.SFSErrorData;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.exceptions.SFSLoginException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;
public class LoginEventHandler extends BaseServerEventHandler
{
#Override
public void handleServerEvent(ISFSEvent e) throws SFSException
{
String email = (String)e.getParameter(SFSEventParam.LOGIN_NAME);
String pass = (String)e.getParameter(SFSEventParam.LOGIN_PASSWORD);
ISession session = (ISession)e.getParameter(SFSEventParam.SESSION);
IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
Connection connection = null;
try
{
connection = dbManager.getConnection();
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE email=?");
stmt.setString(1, email);
ResultSet res = stmt.executeQuery();
if(!res.first())
{
SFSErrorData errData = new SFSErrorData(SFSErrorCode.LOGIN_BAD_USERNAME);
errData.addParameter(email);
throw new SFSLoginException("Bad user name: "+ email, errData);
}
String dbPword = res.getString("password");
int dbId = res.getInt("id");
if(!getApi().checkSecurePassword(session, dbPword, pass));
{
SFSErrorData errorData = new SFSErrorData(SFSErrorCode.LOGIN_BAD_PASSWORD);
errorData.addParameter(email);
throw new SFSLoginException("Bad password for user: "+ email, errorData);
}
session.setProperty("DatabaseID", dbId);
//UNREACHABLE CODE
//IF I COMMENT THIS OUT, THERE IS NO UNREACHABLE CODE ERROR
}
catch(SQLException eve)
{
SFSErrorData erroData = new SFSErrorData(SFSErrorCode.GENERIC_ERROR);
erroData.addParameter("SQL Error: " + eve.getMessage());
throw new SFSLoginException("A SQL Error occurred: " + eve.getMessage(), erroData);
}
finally
{
try
{
connection.close();
}
catch (SQLException e1)
{
}
}
}
}
Your 2nd if statements terminate with ; that is a valid statement. and you are throwing an exception in the next block , that is why the error.
if(!getApi().checkSecurePassword(session, dbPword, pass));
The above if statement terminates with semicolon which is a valid statement, and if statement will act on it, Your other part of the code is executing irrespective of the if statement and that is throwing an exception at the end.
{
SFSErrorData errorData = new SFSErrorData(SFSErrorCode.LOGIN_BAD_PASSWORD);
errorData.addParameter(email);
throw new SFSLoginException("Bad password for user: "+ email, errorData);
}
That is why you are getting the error because your line session.setProperty("DatabaseID", dbId); would never reach.
There is a bogus ; before the previous code block:
if(!getApi().checkSecurePassword(session, dbPword, pass));
// ^
// |
// +---- remove this ';'
{
...
throw new SFSLoginException("Bad password for user: "+ email, errorData);
}
session.setProperty("DatabaseID", dbId);
The throw is therefore always executed, thus the code never reaches session.setProperty().
Because there is an undesired ; just after the second if, the following {} block will always get executed. Which means a SFSLoginException will always be thrown and execution will jump to the catch.
This will result in the setProperty method never getting called.
You need to remove the semicolon from the following statement in your code:
if(!getApi().checkSecurePassword(session, dbPword, pass));

Categories