Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



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

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


suresh anugandula
displaying List of records from database in a jsp using ajax
1 Answer(s)      3 years and 3 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

Advertisement
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
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
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
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
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 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
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
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
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 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
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
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
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
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
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
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
search functionality using jsp from database
search functionality using jsp from database  search functionality using jsp from database
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
how to add data dynamically from database into a dropdown list in a jsp
how to add data dynamically from database into a dropdown list in a jsp  hi friends i am doing a project in jsp and oracle as my database.In my... get dynamically from the database and whenever a new person has registered his
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
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
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
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
Advertisements
 

 

 

DMCA.com