1

I am new to ajax, I am making ajax call, it will hit servlet, it fetches data and prints data to jsp using out.println(). It is working fine but I feel its not good way. Here is my coding ,

Ajax call,

xmlHttpReq.open('GET', "RTMonitor?rtype=groups&groupname="+temp, true);

In RTMonitor servlet I have,

sql ="SELECT a.vehicleno,a.lat,a.lng,a.status,a.rdate,a.rtime from latlng a,vehicle_details b where a.vehicleno=b.vehicleno and b.clientid="+clientid +"  and b.groupid in(select groupid from group_details where groupname='"+gname+"' and clientid='"+clientid+"')";
resultSet = statement.executeQuery(sql);
while(resultSet.next())
{
  response.setContentType("text/html");
  out.println("<tr>"+
   "<td>"+"&nbsp"+"&nbsp"+resultSet.getString("vehicleno")+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"&nbsp"+"<br>"+"<br>"+"</td>"+);
//other <td>s

}

I think this is not good way. So I think about returning response as JSON object. Tell me how to return object as JSON and set values in <td>. and tell me JSON is a good way , or is there any other way please suggest me.

Raghu
  • 1,324
  • 7
  • 24
  • 47

2 Answers2

0

Object to JSON -conversion is explained in question: Converting Java Object to Json using Marshaller

Other things:

  • Your SQL is unsafe! Please refer to the following question that explains prepared statements and has examples too: Difference between Statement and PreparedStatement
  • Generally you should not write your low-level AJAX-code by yourself unless you are aiming to learn things. There are many cross browser functioning Javascript libraries that provide these things in a robust manner, such as JQuery. JQuery's API has the getJSON which you will undoubtedly find very useful (API doc):

     var params = {myObjectId: 1337}; // just some parameters
     $.getJSON( "myUrl/myAjaxAction", params, function( data ) { /* this is the success handler*/
        alert(data.myObject.name); // assuming that returned data (JSON) is: {myObject: {name: 'Hello World!'}}
     });
    
Community
  • 1
  • 1
heikkim
  • 2,955
  • 2
  • 24
  • 34
-1

You should try to avoid as much as possible mixing server-side code with client-side code. Your client-side code should only offer a nice and rich user interface, by manipulating the data which is provided by the server. The server-side code should only process the data - coming from different calls, or taken from a storage, usually a database.

Usually the comunication( asynchrounous or not) from a client and a server goes like that :

  • client sends a request to the server
  • server process the request and it gives a response, usually some html or json/xml
  • client process the response from the server

Ok, now lets move our attention to your specific problem.

Your ajax call : xmlHttpReq.open('GET', "RTMonitor?rtype=groups&groupname="+temp, true); should send the request to the servlet and expect some data back to process and render in a nice way to the user. Your servlet should handle the request, by querying the database( you should definitely change your code so it uses prepared statements as they are preventing SQL injection). By doing so, you've separate your client-side code from server-side code.

private List<YourObject> loadObjectsBySomeLogic() throws SQLException{

    String sql ="SELECT a.vehicleno,a.lat,a.lng,a.status,a.rdate,a.rtime FROM latlng a,vehicle_details b WHERE a.vehicleno=b.vehicleno AND b.clientid= ? AND b.groupid in(select groupid from group_details where groupname= ? and clientid= ?)";

    List<YourObject> list = new ArrayList<YourObject>();//new ArrayList<>(); for Java versions > 1.7
    PreparedStatement ps = null;
    ResultSet rs = null;
    try{
        ps = connection.prepareStatement(sql);
        ps.setLong(1, clientId);
        ps.setString(2, gname);
        ps.setLong(3, clientId);

        rs = ps.executeQuery();
        while(rs .next())
        {
            //load data from ResultSet into an object/list of objects
        }
    }finally{
        closeResources(rs , ps);
    }
    return list;
}

private static final void closeResources(final ResultSet rs , final PreparedStatement ps){
   if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {
            //nasty rs. log the exception?
            LOGGER.error("Could not close the ResultSet!" , e);
        }
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (SQLException e) {
             //nasty ps. log the exception?
            LOGGER.error("Could not close the PreparedStatement!" , e);
        }
    }
}

You could delegate this method to a different object, which handles the business/aplication domain logic, but that's not our point in this case.

You can use Json for your data format, because it has a nice, and easy to understand way to format data, and it is more lightweight compared to XML. You can use any Java library to encode data as Json. I'll provide an example which uses Gson library.

List<YourObject> list = loadObjectsBySomeLogic();
String json = new Gson().toJson(list);
response.setContentType("application/json"); 
response.setCharacterEncoding("UTF-8"); 
response.getWriter().write(json);

Now your Ajax request, should handle the Json data coming from server( I recommend you to use jQuery to make Ajax calls as it's been tested and it works great on all major browsers).

$.get('RTMonitor', function(responseJson) {    
    //handle your json response by rendering it using html + css.           
});
Daniel
  • 1,861
  • 1
  • 15
  • 23
  • Fine I ll Try this and what is LOGGER here – Raghu Aug 21 '14 at 07:28
  • It is a [log4j logger](http://logging.apache.org/log4j/2.x/) . Ignore it for the moment, by changing that line to `e.printStackTrace();`. – Daniel Aug 21 '14 at 07:30
  • I don't quite understand what you mean by more data, but there are cases when you have to handle large amounts of data. In case you are thinking that that sql query will load too many rows, you can limit the numbers of rows to be loaded, by adding limit. This is usually the correspondent of UI pagination. – Daniel Aug 21 '14 at 07:37
  • 1
    @Daniel This kind of PreparedStatement usage does not prevent SQL-injection. This code is as vulnerable as the original. – heikkim Aug 21 '14 at 07:53
  • @Daniel k ... Then there is no limit for data to send through JSon right? because some time my query might return many rows. – Raghu Aug 21 '14 at 09:43
  • I don't think there is a limit, and if there is it must be huge for sure. But you must also consider the case where you have 1 million database records, you don't want your query to fetch and send those 1 million records, encoded as json, to your client, don't you? In this case, you can send 2 parameters through your ajax call to indicate the records which you want to be provided with : `?from=5000&limit=25'. – Daniel Aug 21 '14 at 09:50