Home Answers Viewqa Ajax displaying List of records from database in a jsp using ajax

 
 


suresh anugandula
displaying List of records from database in a jsp using ajax
1 Answer(s)      a year and 10 months ago
Posted in : 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 Anugandula.Suresh@Tata-bss.com
View Answers

July 19, 2011 at 10:36 AM


Use the following:

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









Related Pages:
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
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 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
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
ajax
(top,left and right) using table in jsp. On the left part i am displaying some...ajax  I am facing following problem, I am using ajax to get..., am calling another jsp(two.jsp) which is responsible to get the new data from
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
displaying - Ajax
displaying  hi.. im sending request from ajax page to servlet ..as in response i need the get the from database to servlet and from servlet to ajax in column wise.. i have to display the response column wise in the same
ajax
in a dropdown from database and when i select the empname in dropdwon list and when i click... me reg this. thanks KK   Combobox box using Ajax in JSP   i...ajax  HI, In my application using ajax if i type a managername
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
displaying data   how to display data from database on jsp using struts2
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
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
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
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
Connecting to MySQL database and retrieving and displaying data in JSP page
Connecting to MySQL database and retrieving and displaying data in JSP page... from the database. In this example we will use tomcat version 4.0.3 to run our web application. Creating Table in the database. Using a JDBC driver
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 Rows - JSP-Servlet
Displaying Rows  Hi, I need your support on how to display data from ms sql 2000 database into an html form text box and text area, using java..."); out.println("Display Data from Database"); out.println(""); out.println
List Box - JSP-Servlet
List Box  sir i am developing webb application.am using drop down list box.on selecting one value in list box,i will retrieve values from database and store into another list box in same page using javascript :location.my
JSP and AJAX- very urgent - Ajax
JSP and AJAX- very urgent  Respected Sir/Madam, I am..." button, I have to get a table from the database where all the names starting... (Using AJAX. for ur reference, I have included the coding below: Login.html
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
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
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
Problem displaying resultset in jsp(no frameworks used) - JSP-Servlet
if the resultset return 25 rows, these 25 records are to be displayed in my jsp. My problem area: a) How to display the records within JSP from request>arraylist>...Problem displaying resultset in jsp(no frameworks used)  Problem
displaying in ajax - Ajax
displaying in ajax  hi.. I have an Ajax page ,request gone to server... for the answer  Hi friend, Ajax example to solve the problem : "mainpage.jsp" Ajax Example function postRequest
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
how to fetch the record using AJAX? - Ajax
how to fetch the record using AJAX?  Can anyone tell me how to fetch the records from database using Ajax
Create Listbox in JSP using AJAX control
Create Listbox in JSP using AJAX control  Hi everyone!!! I want... will not type any letter , it gives me entire list from database (stored in Mysql... listbox to select single elemnt using AJAX control . But i don't know anything
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
ajax and jsp code - Ajax
ajax and jsp code  can u please give me the code for retriving the data from database using ajax our requriment is if i select country name in listbox display the corresponding all the states. using jsp and ajax   
JSP Get Data Into Dropdown list From Database
data from the database and set it into the dropdown list in JSP using MySQL...JSP Get Data Into Dropdown list From Database In this section we will discuss... fetching of data into the dropdown list in JSP using Eclipse IDE and the Tomcat 7
AJAX- Database not connected - Ajax
AJAX- Database not connected  Respected Sir/Madam, I am Ragavendran.R.. I am working with AJAX and Database.. Ajax code works fine... only the HTML Contents from JDBC page and Database codings not executed... What
Upload and display image and text records using JSP and Oracle
Upload and display image and text records using JSP and Oracle  Hi all, I'm using JSP and Oracle 10g. I could retrieve and display records from database. But i couldnot retrieve and display image. I want to store
jfreechart displaying chart from access database
jfreechart displaying chart from access database  I have these 2 codes. array.java----in which i retrieve the values from the database . import... javax.servlet.http.HttpServletResponse; /** * * @author AARUSHI */ class database { int roll; String
Jsp and ajax
Jsp and ajax  Hi I am using jsp and ajax.I am retrieving the entire content from database(al.jsp) and put it into a textbox.When i am clicking a combo box,it updates the selected value in the database(jag.jsp
Jsp and ajax
Jsp and ajax  Hi I am using jsp and ajax.I am retrieving the entire content from database(al.jsp) and put it into a textbox.When i am clicking a combo box,it updates the selected value in the database(jag.jsp
Jsp and ajax
Jsp and ajax  Hi I am using jsp and ajax.I am retrieving the entire content from database(al.jsp) and put it into a textbox.When i am clicking a combo box,it updates the selected value in the database(jag.jsp
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
DropDown list
DropDown list  how to get mysql database values into dropdown usign java servlet and ajax?   Here is a jsp code that displays the database...;can u post this code using servlet, i dont want to do in jsp
reading the records from a .xlsx file and storing those records in database table
reading the records from a .xlsx file and storing those records in database table  Here is my requirement, I want to read the records from a .xlsx file and store that records in database table. I tried like this public class
Jsp and ajax
Jsp and ajax  Hi I am using jsp and ajax.I am retrieving the entire content from database(al.jsp) and put it into a textbox.When i am clicking a combo box,it updates the selected value in the database(jag.jsp
Ajax - Ajax
Ajax  I want to get data from database on change event of combobox/list. Suppose I select India through list box then I get all related data from database on that jsp form's textboxes.  Hi friend, Code to help
Displaying Date in jsp - JDBC
Displaying Date in jsp  I want to insert Date of birth of a person in a database.i am getting input value from HTML and i use jsp application to interact with database.My JSP code for inserting Date is below: String dateStr
get files list - Ajax
get files list  Please,friend how to get files list with directories from ftp server or local files on web browser. Thanks, Tin Linn Soe  ...://www.roseindia.net/jsp/ Thanks
list boxs
list boxs  i have two list boxes first list box values from database and i want to assign selected options to the second list box using jsp is it possible to do this in jsp
Name Displaying - JSP-Servlet
Name Displaying  Dear Sir, Please any one help me......... when i enter some value in text that value is already in database dispaly the alert... vijayababu.m@cybermateinfotek.com  Hi AJAX and Servlet var
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 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... * from names"); echo "<p>Select a Name: n"; echo "<Select Name="ID">

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.