Java getter methods returning null instead of the string
When I call getName from MyServ class, I get null, but when I call them locally from DBClass they return strings. anyone know what I'm doing wrong?
package DB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBClass{
private Statement stmt;
private Connection conn;
private ResultSet result;
public String name, surname;
public DBClass(){
}
public Connection dbConnect(final String db_connect_string,
final String db_userid,
final String db_password){
try{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
开发者_StackOverflow中文版 conn =
DriverManager.getConnection(db_connect_string, db_userid,
db_password);
stmt = conn.createStatement();
result = stmt.executeQuery("Select * from .....etc");
if(result.next()){
name = result.getString(1).toString();
surname = result.getString(2).toString();
}
return conn;
} catch(final Exception e){
e.printStackTrace();
return null;
}
}
public String getName(){
return name;
}
public String getSurname(){
return surname;
}
}
package DB;
import java.io.IOException;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MyServ
*/
public class MyServ extends HttpServlet{
private static final long serialVersionUID = 1L;
private final DBClass dbclass;
private final String name, surname;
private final Connection conn;
public MyServ(){
dbclass = new DBClass();
final DBClass db = new DBClass();
conn =
db.dbConnect("jdbc:oracle:thin:@elanweb:1510:xxxxx", "xxxxx",
"xxxxxx");
name = dbclass.getName();
surname = dbclass.getSurname();
}
@Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException{
}
@Override
protected void doPost(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
IOException{
System.out.println("MyServer -- " + name + " " + surname);
response.sendRedirect("http://localhost:8080/DWP/");
}
}
Surely you mean:
name = db.getName();
instead of:
name = dbclass.getName();
You seem to be referencing the wrong variable within the constructor, the one without an open connection (dbclass).
Simply because the value is null
(which is a String, kind of).
Look at the relevant bits of the code. In your MyServ
constructor, you do:
dbclass = new DBClass();
According to the DBClass constructor, this initialises all fields to default values (which for a String is null
).
Then you don't use this variable again until you call:
dbclass.getName();
which correctly goes and looks up the name
variable - which is null, because it was implicitly assigned null when the object was constructed - and returns this to you.
Perhaps a better question is, what did you expect it to return, and why?
精彩评论