Null Pointer Exception in java servlets pages [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Im very beginner in Java servlets... i have tried to connect servlet with database but NullPointerException
I tried to resolve this problem ,but no luck...
Error is
java.lang.NullPointerException
JDBCServlet.service(JDBCServlet.java:(42)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.DriverManager;//1
import java.sql.Connection;//2
import java.sql.SQLException;
import java.sql.Statement;//3
import java.sql.ResultSet;//4
public class JDBCServlet extends HttpServlet {
Connection con;
Statement st;
ResultSet rs;
String sql;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("JDBC Servlet Invoked");
//1st step: load JDBC MySql Drivers
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Drivers Loaded");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2nd Step: create a connection
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/webtech1", "root", "123456");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sql = "select * from user";
try {
st = con.createStatement();
rs = st.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("firstName"));
System.out.println(rs.getString("lastName"));
System.out.println(rs.getString("email"));
System.out.println(rs.getString("password"));
System.out.println(rs.getString("createdate"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Please put null checks on your con,st,rs objects. And also double check your mysql connection string.

You have initialised String sql twice. One as a property and one as a local variable i.e.
String sql = "select * from user";
Later, you are calling sql (an instance variable) which is indeed of null value, which causes null pointer exception. You just need to remove String declaration from the body of your service method.

Related

How to use ResultSet returned by java method in SOAPUI with groovy script?

We have created jar file for a java method and imported it in SOAPUI. We are able to call method, however not able to retrieve query result returned in ResultSet by java method in groovy script def dataRow = GetData.GetRecords(preQuery). I am new to groovy script.
Below is method we have written in java and created jar for it.
package getRecords;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class GetData {
protected static Connection con = null;
protected static Statement stmt = null;
protected static ResultSet result = null;
//Opening DB connection
public static void OpenDBConnection(String dbUrl, String driver, String username, String password){
//Making connection to DB
try {
Class.forName(driver);
con = DriverManager.getConnection(dbUrl, username, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Closing DB connection
public static void CloseDBConnection(){
try {
//Closing DB connection
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Executing query and fetching data from DB
public static ResultSet GetRecords(String query){
//Executing query and saving result into result set
try {
stmt = con.createStatement();
result = stmt.executeQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void main(String args[]){
System.out.println("DBConnection..");
GetData gd = new GetData();
GetData.OpenDBConnection("jdbc:oracle:thin:#test:1530/test", "oracle.jdbc.driver.OracleDriver", "******", "******");
System.out.println("DB");
}
}
I suspect your result set is being closed when you return from GetRecords (tip: use camel case for Java method names, starting with a lower-case character) and you may also be jumping JVMs. See also Is it Ok to Pass ResultSet?.
You probably don't need to use your result set as a result set back in soapUI, you just want the data, so a better option would be to populate a bean and return a List of those instead:
public static List<MyBean> GetRecords(String query){
List<MyBean> myBeans = new ArrayList<>();
//Executing query and saving result into result set
try {
stmt = con.createStatement();
result = stmt.executeQuery(query);
while (result.next()) {
MyBean myBean = new MyBean();
// Populate the bean...
myBeans.add(myBean);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return myBeans;
}
You might also want to investigate the try-with-resources feature that came out with Java 7: it'll handle the closing of your connections automatically.
In SoapUi you can directly do the JDBC call using Groovy scripting.
If you wanted to do some Database operation in soapUI you can write the code in groovy using the corresponding database driver ( DB2, Oracle, Mysql), Until or unless any specific reason to use jar file as you have mentioned.
Making the database connection you need to download and place the jar files inside ( SoapUi install folder/bin/ext
eg.. for Oracle (ojdbc6.jar, orai18n.jar)

Unreachable catch block for ClassNotFoundException. This exception is never thrown from the try statement body

Here is the code for simple login Servlet in Eclipse which checks username and password from the existing table of database and take it to home page if exists or send to login page. When I run it on server and put information in login page it shows following error. can you help for that please. thank you.
1. Error to solve
root cause
java.lang.Error: Unresolved compilation problem:
Unreachable catch block for ClassNotFoundException. This exception is never thrown from the try statement body
com.loginapps.servlets.LoginServlet.doGet(LoginServlet.java:90)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
Coding
package com.loginapps.servlets;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*** Servlet implementation class LoginServlet* #param <con>*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection con;
PreparedStatement pst;
public void init(ServletConfig config) throws ServletException {
String dname = config.getInitParameter("drivername");
String uname = config.getInitParameter("username");
System.out.println(dname);
System.out.println(uname);
try{
Class.forName(dname);
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/logindb",uname,"");
}
catch(SQLException e){
e.printStackTrace();
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
String uname = request.getParameter("txtuname");
String pwd = request.getParameter("txtpwd");
session.setAttribute("username",uname);
try {
pst = con.prepareStatement("select * from users where username = ? and password = ?");
pst.setString(1,uname);
pst.setString(2,pwd);
ResultSet rs = pst.executeQuery();
if(rs.next()){
response.sendRedirect("home.jsp");
}
else {
response.sendRedirect("login.html");
}
}
catch(SQLException e){
e.printStackTrace();
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
The error you posted:
Unreachable catch block for ClassNotFoundException. This exception is never thrown from the try statement body
Your catch block is the problem:
catch(ClassNotFoundException e){
e.printStackTrace();
}
ClassNotFoundException is a checked exception and is never thrown by the code inside your try block - see this page
I have removed catch(ClassNotFoundException e) in doGet method. It is working fine.
ClassNotFoundException is a checked exception and it will never occur in your doGet method code.

Simple Java web service connecting to mySql not working [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I decided to try to connect a java client to a mysql db running on wamp.
Can anybody tell me why im getting this runtime problem?
My DBConnect() class
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DbConnect {
private Connection conn;
private Statement statement;
private ResultSet resultset;
public DbConnect(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://xxx.xxx.xxx.xxx:3306/pk","root","");
} catch (Exception e){
System.out.println("Error: " + e);
}
}
public String getData(){
String result ="";
try {
resultset = statement.executeQuery("select * from data_user");
while(resultset.next())
{
result+=resultset.getString("userFirstName");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
My main() class
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
DbConnect conn = new DbConnect();
System.out.println(conn.getData());
}
My error at runtime
Error: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
The last packet sent successfully to the server was 0 milliseconds
ago. The driver has not received any packets from the server.
Exception in thread "main" java.lang.NullPointerException at
DbConnect.getData(DbConnect.java:26) at Main.main(Main.java:8) ERROR:
JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [util.c:840]
}
Offending line
resultset = statement.executeQuery("select * from data_user");
It looks like you didnt instantiate your statement, unless you are missing some code. You need to do something like the following: statement=conn.createStatement();
Take a look at this example

Unable to connect to mySQL database using JSP

I'm trying to establish a connection to my database using the following servlet: (the work is done in the doGet method)
package demo;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Connect")
public class Connect extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Connect() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
out.println("Unable to load database.");
return;
}
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc.mysql://localhost:3306/jakesdb", "root", "sixTeen58");
} catch (SQLException e) {
out.println("Unable to connect to the database.");
return;
}
//// Connected to database. do some work here ////////////
out.println("Connected to the database!");
///////////////////////////////////////////////////////////
try {
conn.close();
} catch (SQLException e) {
out.println("Unable to close connection to database.");
}
}
}
However, I am always getting hung up at
try {
conn = DriverManager.getConnection("jdbc.mysql://localhost:3306/jakesdb", "root", "sixTeen58");
} catch (SQLException e) {
out.println("Unable to connect to the database.");
return;
}
I have verified using sql workbench that the username (root) and password (sixTeen58) are correct, and the port is indeed 3306. I have mysql-connector-java-5.1.36.zip in my libraries and it's linked properly. I'm not sure what is going on but every time I just see "Unable to connect to the database" when I run the page.
Any idea what I'm doing wrong?
You did a minor mistake. You need colon : instead of . at database URL of getConnection method. Change like:
"jdbc:mysql://localhost:3306/jakesdb" // Use : instead of .

Connection Timeout while running sql procedure from servlet

I want to run a procedure which takes approx 15 minutes to run in sql environment. Whereas when I am trying to run it using Servlet I am getting Network error(TCP error). I am using Http Server using ajp to transfer request to Tomcat server. This is my code. can anybody tell me what is going wrong here.
import com.itech.softensity.utils.Utils;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
public class JdbcServlet extends HttpServlet
{
protected static Logger logger = Logger.getLogger(JdbcServlet.class);
static final String jtdsurl = "jdbc:jtds:sqlserver://<server_name>;instance=<instance>;DatabaseName=<databasename>;socketTimeout=100000;socketKeepAlive=true";
static final String USER = "username";
static final String PASS = "password";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Connection con = null;
CallableStatement stmt = null;
ResultSet result =null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
logger.info("Connecting to database...");
con = DriverManager.getConnection(jtdsurl, "username","password");
logger.info("Creating statement...");
String sql = "exec populateMobRefLit";
stmt = con.prepareCall(sql);
stmt.setQueryTimeout(100000);
stmt.executeQuery();
logger.info("Executing stored procedure check new...");
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
logger.info("Procedure run successfully values: ");
}
catch (Exception e) {
try {
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
}catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
logger.info(Utils.stackTraceToString(e));
}
finally{
try {
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have tried it with JTDS driver as well as microsoft provided jdbc driver as the drivers have specific timeouts. I have tried Hibernate, I have tried Spring, but nothing works.

Categories