displaying List of records from database in a jsp using ajax

Ads
 

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">

Ads









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
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
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
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
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
search functionality using jsp from database
search functionality using jsp from database  search functionality using jsp from database
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
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
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
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
<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
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
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
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 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 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
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
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 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
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 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

Ads