displaying List of records from database in a jsp using ajax

displaying List of records from database in a jsp using ajax

Sir, I need to retrieve the records from the database for every 7 seconds and display those records in a jsp.Following is my code.

x.jsp:

    <%@page import="com.tbss.RealDAO"%>
    <%@page import="java.util.List"%>
    <%@page import="com.tbss.RtChannels"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <html>
    <head>
    <script type="text/javascript" language="javascript">

         function postRequest(strURL) {
            //document.writeln("pr");       
                if (window.XMLHttpRequest) { // Mozilla, Safari, ...
                 var xmlHttp = new XMLHttpRequest();
                }else if (window.ActiveXObject) { // IE
                 var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                  }
                xmlHttp.open('POST', strURL, true);
                //xmlHttp.setRequestHeader
                  //    ('Content-Type', 'application/x-www-form-urlencoded');
                //document.writeln("pr1");
                xmlHttp.onreadystatechange=function(){processRequest(xmlHttp);};


             xmlHttp.send(null);

         }
        function processRequest(xmlHttp) 
        { 
            //document.writeln("prq");
            if (xmlHttp.readyState == 4) 
            { 
                if(xmlHttp.status == 200) 
                { 
                    //get the XML send by the servlet 
                    var profileXML = xmlHttp.responseXML.getElementsByTagName("Profile")[0]; 

                    //Update the HTML 
                   updateHTML(profileXML);
                else 
                { 
                    alert("Error loading page\n"+xmlHttp.status+":"+xmlHttp.statusText); 
                } 
            } 
        } 

          /** 
        * This function parses the XML and updates the  
        * HTML DOM by creating a new text node is not present 
        * or replacing the existing text node. 
        */ 
       function updateHTML(profileXML) 
        { 
                document.writeln("updateHTML");
                //The node valuse will give actual data 
                var profileText = profileXML.childNodes[0].nodeValue; 

                //Create the Text Node with the data received 
                var profileBody = document.createTextNode(profileText); 

                //Get the reference of the DIV in the HTML DOM by passing the ID 
                var profileSection = document.getElementById("display"); 

                //Check if the TextNode already exist 
                if(profileSection.childNodes[0]) 
                { 
                    //If yes then replace the existing node with the new one 
                    profileSection.replaceChild(profileBody, profileSection.childNodes[0]); 
                } 
                else 
                { 
                    //If not then append the new Text node 
                    profileSection.appendChild(profileBody); 
                }    

        } 

        function calls(){
            //document.writeln("before");
            postRequest('/AutoDialer/refreshServlet');

        }
    </script>
    </head>
    <body onload="calls()">
    <div id="display">
        <table border="5">
              <tr>
                <th>COMPAIGN_ID</th>
                <th>RECORD_ID</th>
                <th>SESSION_ID</th>
                <th>CONNECTEDPHONE</th>
                <th>SESSION_DURATION</th>
              </tr> 

            <c:forEach var="rc" items="${listKey}"> 
                <tr bgcolor="grey">     
                    <td><c:out value="${rc.compaignID}"></c:out></td>
                    <td><c:out value="${rc.recordID}"></c:out></td>
                    <td><c:out value="${rc.sessionID}"></c:out></td>
                    <td><c:out value="${rc.connectedPhone}"></c:out></td>
                    <td><c:out value="${rc.sessionDuration}"></c:out></td>
                </tr>
            </c:forEach>
             </table>
    </div>
    </body>
    </html>


In between the <div></div> I have to display the records. I am displaying the records using jstl tag libraries. But it is not working. I think it is not right way. I have written a following servlet to get the records from the database dynamically. 

  - RefreshServlet.java

     package com.tbss;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RefreshServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 6523265408718669299L;
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("servlet");
        HttpSession session=request.getSession();
        PrintWriter out=response.getWriter();
        // TODO Auto-generated method stub
        response.setContentType("text/xml");          
        response.setHeader("Cache-Control", "no-cache");
        List<RtChannels> list;
        RealDAO rdao=new RealDAO();
        rdao.store();
        list=rdao.getRecords(); 
        System.out.println("list: "+list);
        session.setAttribute("listKey",list);
        List<RtChannels> list1=(List<RtChannels>) session.getAttribute("listKey");
        //out.print(list1);
        out.print("<Profile><![CDATA[" + list1 + "]]></Profile>");
        out.close();
    }
}


Here am getting the records as a list of pojo classes. I have to display these list of records in between <div></div>. Following is my DAO class

  - RealDAO.java

   package com.tbss;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.timesten.jdbc.TimesTenConnection;
import com.timesten.jdbc.TimesTenDataSource;

public class RealDAO implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 7075169571642208856L;
    long s,e;
    TimesTenConnection ttcon;
    TimesTenDataSource ttds;
    Statement stmt;
    ResultSet rset;
    Date start=null,end=null;
    DateFormat df=new SimpleDateFormat("HH:mm:ss");
    public RealDAO() {

    }
    public void store(){
        start=new Date();
        String startString=df.format(start);


        try {
            ttds = new TimesTenDataSource(); 
            ttds.setUrl("jdbc:timesten:client:dsn=ttc1;UID=ttsa;PWD=abc123"); 
            ttcon = (TimesTenConnection) ttds.getConnection();
            stmt = ttcon.createStatement();
            //ttds.setLoginTimeout(30);
            stmt.executeUpdate("insert into RT_CHANNELS values(1,1,'a1',9581135170)");
            stmt.executeUpdate("insert into RT_CHANNELS values(2,2,'a2',9985424475)");
            stmt.executeUpdate("insert into RT_CHANNELS values(3,3,'a3',9885922704)");
            stmt.executeUpdate("insert into RT_CHANNELS values(4,4,'a4',9849281031)");
            stmt.executeUpdate("insert into RT_CHANNELS values(5,5,'a5',9490183642)");
            stmt.executeUpdate("insert into RT_CHANNELS values(6,6,'a6',9246543352)");
            stmt.executeUpdate("insert into RT_CHANNELS values(7,7,'a7',9595959595)");
            stmt.executeUpdate("insert into RT_CHANNELS values(8,8,'a8',5956565656)");
            stmt.executeUpdate("insert into RT_CHANNELS values(9,9,'a9',4854232125)");
            stmt.executeUpdate("insert into RT_CHANNELS values(10,10,'a10',8956565555)");
            s=start.getTime();
            ttcon.commit();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{
            try {
                stmt.close();
                ttcon.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public List<RtChannels> getRecords(){
        List<RtChannels> list=new ArrayList<RtChannels>();
        try { 
             ttds = new TimesTenDataSource(); 
             ttds.setUrl("jdbc:timesten:client:dsn=ttc1;UID=ttsa;PWD=abc123"); 
             ttcon = (TimesTenConnection) ttds.getConnection();
             stmt = ttcon.createStatement();
             ttds.setLoginTimeout(30);
             // create the TimesTen data source and set the connection URL
             //ttcon.setTtPrefetchClose(false);
             rset=stmt.executeQuery("select * from rt_channels");
             while(rset.next()) { 
                 RtChannels rp=new RtChannels();
                 rp.setCompaignID(rset.getLong("CAMPAIGN_ID"));
                 rp.setConnectedPhone(rset.getLong("CONNECTEDPHONE"));
                 rp.setRecordID(rset.getLong("RECORD_ID"));
                 rp.setSessionID(rset.getString("SESSION_ID"));
                 end=new Date();
                 String endString=df.format(end);
                /* int endInt=Integer.parseInt(endString);*/
                 e=end.getTime();
                     rp.setSessionDuration(endString);
                 rp.setSessionDuration("00:00:00");
                 start=end;
                 list.add(rp);
              } 
              //System.out.println("return");
        } catch(SQLException e) { 
            e.printStackTrace();
        } 
        finally{
            try {
                //System.out.println("getrecordfinal");
                rset.close();
                stmt.close();
                ttcon.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }       
        return list;
    }
}

And ajax code is not fetching the updated data from the database. After getting the response from the servlet am unable to display the records. please help me in resolving this problem. Please send me your answer to [email protected]
View Answers

July 19, 2011 at 10:36 AM

Use the following:

<META HTTP-EQUIV="Refresh" CONTENT="7">









Related Tutorials/Questions & Answers:
displaying List of records from database in a jsp using ajax
displaying List of records from database in a jsp using ajax  Sir, I need to retrieve the records from the database for every 7 seconds and display...; In between the <div></div> I have to display the records. I am displaying
displaying List of records from database in a jsp using ajax, onclick it should display the results ?? its urgent can u help me
displaying List of records from database in a jsp using ajax, onclick it should display the results ?? its urgent can u help me   displaying List of records from database in a jsp using ajax, onclick it should display the results
Advertisements
3 dropdown list from the database using JSP
3 dropdown list from the database using JSP  Hi, I'm new to JSP I want to create 3 dropdown list each depend on the other and get the options from the database using JSP
how to generate reports from oracle database using jsp and ajax code
how to generate reports from oracle database using jsp and ajax code  Hai masters i am new to this Java world. my team leader ask me to generate sales report data from oracle database to jsp page please any one know how to do
Data displaying with limited records in jsp
Data displaying with limited records in jsp  How to display table with limited 10 records , after clicking next button another 10 records from database upto last record please help me
displaying data retrieved from a database in a jsp page
displaying data retrieved from a database in a jsp page  the page should display username, emailid, telephone in addition to tthe tagline however... sql = "select billid, customerid, billdate, status from customerbills where
jsp programe for displaying data from database
jsp programe for displaying data from database  i am using JSP.i want to insert data into database and also want to display the things i have entered.../WebSevices/19592-retriving-data-from-sql-server-using-jsp-code-and-placing-them
jsp programe for displaying data from database
jsp programe for displaying data from database  i am using JSP.i want to insert data into database and also want to display the things i have entered.../WebSevices/19592-retriving-data-from-sql-server-using-jsp-code-and-placing-them
jsp programe for displaying data from database
jsp programe for displaying data from database  i am using JSP.i want to insert data into database and also want to display the things i have entered.../WebSevices/19592-retriving-data-from-sql-server-using-jsp-code-and-placing-them
retrieving newly added records from mssql database and display in a jsp
retrieving newly added records from mssql database and display in a jsp ... from mssql database table and display those records in a jsp.And i have to delete these 10 records from the jsp and retrieve the next recently added 10 records
Retrieving newly inserted records and displaying in jsp forever
Retrieving newly inserted records and displaying in jsp forever  Sir, here is my requirement, First i have to retrieve newly added 10 records from... of every record which is displayed on the jsp (not in database) and immediately i have
search functionality using jsp from database
search functionality using jsp from database  search functionality using jsp from database
Displaying file from database
Displaying file from database  I have list of files in my database. I... that corresponding file from database. I have list of file id related to search. I want to retrieve and display all the file using list of file ID. Is there is any other way
using jsp's....and ajax - Ajax
using jsp's....and ajax  Hi, i need code using ajax .....in a text box when i enter an alphabet i should get list of words starts with the alphabet given in the text box
How to get data from DB in to Text box by using Jsp & Ajax
How to get data from DB in to Text box by using Jsp & Ajax   I want to get the data from database in to text box in a jsp page by using Ajax. If I... with a and from that i need to select the required value and i should store
save multiple records into database using jsp/servlet mvc
save multiple records into database using jsp/servlet mvc  hai, this is my jsp where i have enter multiple username and password and save it to database in single hit user.jsp <form action="UserServlet" method="post
How to retrieve image from database using jsp and servlet?
How to retrieve image from database using jsp and servlet?  Hi, I am trying to find code for displaying the image from database in a JSP page. How to retrieve image from database using jsp and servlet
Hi, I'm new to JSP I want to create 3 dropdown list each depend on the other and get the options from the database using JSP
Hi, I'm new to JSP I want to create 3 dropdown list each depend on the other and get the options from the database using JSP  as i said i want... the database using JSP. like country,state,city..please guide me
access image from ajax store in mysql using jsp
access image from ajax store in mysql using jsp  access image from ajax store in mysql using jsp (code to access image captured by camera and store in mysql
how to display records from database
how to display records from database  I want to display records from database in tables, the database is having 2000 records and i want to display 20 records at a time and to use next and previous link buttons to show
displaying employee records and their images problem - JSP-Servlet
displaying employee records and their images problem  hi, Thanks for your reply to my question. The code you sent to me yesterday.... the structure of my database is: emp_id int; picture blob; first
displaying images and records problem - JSP-Servlet
displaying images and records problem  hi, Thanks for your reply... it, all what i want is to display staff records and their pictures on the web pages... database is: emp_id int; picture blob; first_name varchar(50); last_name
<img src=""> using retrieve image from database using jsp
using retrieve image from database using jsp  how to <img src="" > tag using retrieve image from database and display in jsp
Retrieve database from the table dynamically in jsp from oracle using servlet
Retrieve database from the table dynamically in jsp from oracle using servlet  Sir, I have created a table in oracle using eclipse, and added few... using java servlet from the database in the jsp page
Displaying image using jsp and spring.
Displaying image using jsp and spring.  how to display an image stored in WEB-INF/images folder on the browser using jsp and spring
How to insert or delete records in MS access database using jsp - JSP-Servlet
How to insert or delete records in MS access database using jsp  Hi friends please provide me a solution that i insert or delete record from a database using java server pages. I used the microsoft access 2003 database. PlZ
retrive data from database using jsp in struts?
retrive data from database using jsp in struts?   *search.jsp* <%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%> <... searchProduct(SearchDTO sdto) { String query="select * from product
select value from autocomplete textbox using jquery in jsp from database.
select value from autocomplete textbox using jquery in jsp from database.  Hii Sir, Lots of thnx to ur reply .I went through both... of selecting value from autocomplete textbox using jquery in jsp from mysql database
select value from autocomplete textbox using jquery in jsp from database.
select value from autocomplete textbox using jquery in jsp from database. ... but was unable to find out exact way to fullfill the solution of selecting value from autocomplete textbox using jquery in jsp from mysql database. Kindly send me
displaying both image and records problem in jsp and servlet - JSP-Servlet
displaying both image and records problem in jsp and servlet  hello... the application to display more than one employee records and their pictures. e.g. say i'm having records like: firstname, lastname, empid, department, salary, job_title
retrive image from database using jsp without stream
retrive image from database using jsp without stream  How to retrive image from database using jsp without stream like (inputStream
JSP Get Data Into Dropdown list From Database
JSP Get Data Into Dropdown list From Database In this section we will discuss... for fetching data from the database and set it into the dropdown list in JSP... fetching of data into the dropdown list in JSP using Eclipse IDE and the Tomcat 7
retrieve related data from database using jsp and mysql
retrieve related data from database using jsp and mysql  Hi sir, please give some example of jsp code for retrieving mysql database values in multiple dropdown list. if we change a value in a dropdown its related value must
fetch record from oracle database using jsp-servlet?
fetch record from oracle database using jsp-servlet?  how can i fetch data from oracle database by using jsp-servlet. i'm using eclipse, tomcat server and oracle database and creating jsp pages and also using servlet
Ajax using jsp
Ajax using jsp  <%@ page import="java.io.*" %> <%@ page...); } %> Is there Any error...........In first Page I use ajax for displaying the data from database and edit that data...that edit data is used in the above
Populate dropdown menu from database using jsp and servlet
Populate dropdown menu from database using jsp and servlet  please i need code to populate dropdown menu from mysql database using jsp and servlet. thanks
How to display image in jsp from database using Servlet?
How to display image in jsp from database using Servlet?  Hi, How to display image in jsp from database using Servlet? Thanks   Hi, You will find code and example program at Retrieve image from database using Servlet
retrive the employee details with image from mysql database using jsp servlet
retrive the employee details with image from mysql database using jsp servlet  im doing the web project to retrive the employee profile which i stored in the database using jsp servlet then want to show the result in the next jsp
Read code from excel sheet and upload into database using JSP
Read code from excel sheet and upload into database using JSP  I want to upload data to database from an excel worksheet using jsp ...Please help
retrive the data from access database to drop down list box in jsp
retrive the data from access database to drop down list box in jsp  hai, im new to jsp now im using the jsp along with access database.in table i load all the data's i need to retrive the data from database to dropdown list box
Retrieve image from database using servlet and display in JSP
Retrieve image from database using servlet and display in JSP  Hi, I am total new to JSP although I am learning it for the last few days. Now I want to use MySQL Database from JSP page. How to retrieve image from database using
how to display values from database into table using jsp
how to display values from database into table using jsp  I want to display values from database into table based on condition in query, how... the values from database based on the bookname or authorname entered must be display
Read data from excel file and update database using jsp
Read data from excel file and update database using jsp  read data from excel file and update database using jsp Hi, I am using a MySQL database... upload excel file and update database using JSP ? Thanks in Advance
displaying data for a single column from Mysql database in the list box in php form
displaying data for a single column from Mysql database in the list box in php form  I have a form in php.want to display data from a single column...('include/functions.php'); $Select = "SELECT * FROM category_master"; $Q = mysql
Values from servlet into dropdownlist in jsp page using ajax
Values from servlet into dropdownlist in jsp page using ajax  1) jsp...=s.executeQuery("select * from country"); while(rs.next...=st.executeQuery("select coun_id from country where coun_name= '"+country
view data from database using drop down list
view data from database using drop down list  hi i want to view the data from database by selecting a value in a drop down list. for an example drop down list have picture element.when click it select pictures from the database
How to get the data from the database using Servlet or JSP program
How to get the data from the database using Servlet or JSP program  ... database using JSP Get data from database using JSP... from the database like oracle . I have created one jsp program like this <
how to read values from excel sheet and compare with database using jsp
how to read values from excel sheet and compare with database using jsp ... with database using jsp coding i.e, if i have 6(assetid,assetname,serialno,cubical... to database from excelsheet
connect to the database from JSP
connect to the database from JSP  How do you connect to the database from JSP?   A Connection to a database can be established from a jsp page by writing the code to establish a connection using a jsp scriptlets
Data needs to be gathered in XML file from the database (MySql) using JSP
data regarding particular id from the database table. Data needs to be gathered in XML file from the database (MySql) using appropriate JSP/Java Bean functions...Data needs to be gathered in XML file from the database (MySql) using JSP 

Ads