0
String Dept  = request.getParameter("dept");
int NumOfEmp = Integer.parseInt(request.getParameter("EmployeeNum"));

if(null != Dept && !Dept.isEmpty()){
       // add criteria for Name
      query += " AND DeptName = '"+ Dept + "'"; // prefer parametrized query
    }

    if(NumOfEmp > 0){

        // add criteria for Age
      query += " AND NumberOfEmployees = "+ NumOfEmp ;  // prefer parametrized query
    }

System.out.println("QUERY ......... " +  query);
pst = c.prepareStatement(query);

The query that gets formed looks just fine :

here is what I got:

select DeptName, NumberOfEmployees from Departments where 1 = 1 AND 

         NumberOfEmployees = 50

The query looks good to me but just after printing the query, noting is printed on console. Then If I explicitly call the url, it gives an exception that says:

 Exception java.lang.NumberFormatException: null

Data string that I passed from ajax:

var dataString ={ "EmployeeNum" : "50"};

How I can I resolve this ?What seems to be the issue here ?

Edit : Here is the complete code:

package com.Charts;

/**
 * Servlet implementation class DBChart
 */
@WebServlet("/db")
public class DBChart extends HttpServlet
{
Connection c = null;
//Statement st = null;
ResultSet rs = null;
String query = null;
JSONObject obj = null;
JSONObject resobj =null;
PreparedStatement pst = null;
//DatabaseMetaData dbmd = null;
String dbURL="jdbc:sqlserver://localhost:1433; databaseName = EMPLOYEE";
String user = "sa";
String password = "minisiminoni";
public  void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
try
{
List<JSONObject> Details = new LinkedList<JSONObject>();
PrintWriter out = response.getWriter();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
c = DriverManager.getConnection(dbURL, user, password);
query = "select DeptName, NumberOfEmployees from Departments where 1 = 1";
String Dept = "";
try
{
Dept  = request.getParameter("dept");
}
catch(Exception e)
{
System.out.println("request param dept " + e);
}
String EmployeeNum= "";
try
{
 EmployeeNum = request.getParameter("EmployeeNum");
}
catch(Exception e)
{
System.out.println("error in get param" + e );
}
int NumOfEmp;
try {
    NumOfEmp = Integer.parseInt(EmployeeNum);
} catch(NumberFormatException e){
    StringBuilder sb = new StringBuilder();
    sb.append("Error parsing this EployeeNum: ");
    sb.append(EmployeeNum);
    e.printStackTrace();
    throw new RuntimeException(sb.toString());
}

if (Dept != null && !Dept.isEmpty()) {
      // add criteria for Name
      query += " AND DeptName = '"+ Dept + "'"; // prefer parametrized query
    }
    if (NumOfEmp > 0) {
     // add criteria for Age
      query += " AND NumberOfEmployees = "+ NumOfEmp ;  // prefer parametrized query
    }
System.out.println("QUERY ......... " +  query);
pst = c.prepareStatement(query);
resobj = new JSONObject();
while(rs.next())
{
String DeptName = rs.getString(1);
System.out.println("name " + DeptName);
int NumberOfEmployees = rs.getInt(2);
System.out.println("num " + NumberOfEmployees );
obj = new JSONObject();
obj.put("DeptName", DeptName);
obj.put( "NumberOfEmployees",NumberOfEmployees );
Details.add(obj);
}
resobj.put("Details", Details);
out.write(resobj.toString());

}
catch(Exception e)
{
System.out.println("Exception " + e);  //only this is where exception is caught
}
}
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     doGet(request, response);
  }
}

Console :

INFO: QUERY ......... select DeptName, NumberOfEmployees from Departments where 1 = 1 AND NumberOfEmployees = 50
2015-03-27T14:32:30.604+0530|SEVERE: SLF4J: The requested version 1.6 by your slf4j binding is not compatible with [1.5.5, 1.5.6]
2015-03-27T14:32:30.604+0530|SEVERE: SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.

After then nothing :

Then if I explicitly go to servlet URL , I get this :

2015-03-27T14:33:58.670+0530|INFO: Exception java.lang.NumberFormatException: null

Here is my ajax call:

<script type="text/javascript">
            var dataString ={ "EmployeeNum" : "50"};
            var queryObject="";
            var queryObjectLen="";
            console.log("loading");
            google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(function() {
    $.ajax({
        type : 'POST',
        data:  dataString,
        url : 'http://localhost:8080/Charts/db',
        success : function(data) {
        alert("success");
            queryObject = jQuery.parseJSON(data);            
            queryObjectLen = queryObject.Details.length;
            console.log("queryObj: "+queryObject+" Length: "+queryObjectLen);
            drawChart();
        },
        error : function(xhr, type) {

            alert('server error occoured')
        }
    }).done(function(msg) {
            alert("aa gya Response: " + msg);
        });
});
Simran kaur
  • 27
  • 1
  • 7

1 Answers1

1

There are many corrections to your code

1st : SQL Query
Do you really need this 1 = 1 it smeels like SQL Injection.. so remove it

2nd Java Code
A. Always try{}catch(){} code blocks that can generate an exception;
B. Always print a comprehensive error message;
C. it is a must to use log4j for ex;

3rd Business rules
A. You must check if number of employees is as you expect it Great or Equal to Zero
B. Prevent your Code from SQL Injection

Try with this code

String Dept  = request.getParameter("dept");
String EmployeeNum = request.getParameter("EmployeeNum");
try {
    int NumOfEmp = Integer.parseInt(EmployeeNum);
} catch(NumberFormatException e){
    StringBuilder sb = new StringBuilder();
    sb.append("Error parsing this EployeeNum: ");
    sb.append(EmployeeNum);
    e.printStackTrace();
    throw new RuntimeException(sb.toString());
}

if (Dept != null && !Dept.isEmpty()) {
      // add criteria for Name
      query += " AND DeptName = '"+ Dept + "'"; // prefer parametrized query
    }
    if (NumOfEmp > 0) {
     // add criteria for Age
      query += " AND NumberOfEmployees = "+ NumOfEmp ;  // prefer parametrized query
    }
System.out.println("QUERY ......... " +  query);
pst = c.prepareStatement(query);
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45
  • Hey, I tried this and I still have exactly the same behavior. I get exception when I explicitly call the url otherwise console prints untiil query is formed and then nothing at all. – Simran kaur Mar 27 '15 at 09:12