Displaying XML data in JSP page

Here is an example in which XML content is accessed to display in JSP page.  We have XML file which contain some books data, which has been displayed in JSP in a table format.

In this example DocumentBuilderFactory class is used for factory API. Then DocumentBuilder type db is created to convert XML file to Document doc. Then each node has accessed in the NodeList and the value of each NodeList (nl) is printed using its indexes.

test.xml

<bookstore>
 <book category="COOKING">
 <title lang="en">Everyday Italian</title>
 <author>Giada De Laurentiis</author>
 <year>2005</year>
 <price>30.00</price>
 </book>
 <book category="CHILDREN">
 <title lang="en">Harry Potter</title>
 <author>J K. Rowling</author>
 <year>2005</year>
 <price>29.99</price>
 </book>
 <book category="WEB">
 <title lang="en">Learning XML</title>
 <author>Erik T. Ray</author>
 <year>2003</year>
 <price>39.95</price>
 </book>
</bookstore>

displayXML.jsp

<%@ page contentType="text/html"%>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory,
javax.xml.parsers.DocumentBuilder,org.w3c.dom.*"
%>
<%
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("http://localhost:8080/practice/test.xml");

NodeList nl= doc.getElementsByTagName("title");
NodeList n2= doc.getElementsByTagName("author");
NodeList n3= doc.getElementsByTagName("year");
NodeList n4= doc.getElementsByTagName("price");
%>
<html>
<body><center>
 <table width="500" border="0" cellspacing="0" cellpadding="0">
 <tr>
 <td style="background:#000033;color:#FFFFFF;font-weight:bold;">Title</td>
 <td style="background:#000033;color:#FFFFFF;font-weight:bold;">Author</td>
 <td style="background:#000033;color:#FFFFFF;font-weight:bold;">Year</td>
 <td style="background:#000033;color:#FFFFFF;font-weight:bold;">Price</td>
 </tr>
 <tr>
 <%
 for(int i=0;i<3;i++)
 {
 %>
 <td><%= nl.item(i).getFirstChild().getNodeValue() %></td>
 <td><%= n2.item(i).getFirstChild().getNodeValue() %></td>
 <td><%= n3.item(i).getFirstChild().getNodeValue() %></td>
 <td><%= n4.item(i).getFirstChild().getNodeValue() %></td>
 </tr>
 <%
 }
 %>
 </table>
 </center>
</body>
</html>

Actually I was trying to display these XML data by using loop. But I did not get any solution to read the total number of node in the XML file from JSP. So Readers, if you got any solution for my problem, please write me.

Auto refreshing the content without reloading page, using JQuery

In my previous post I have given some tips to select multiple rows from a database table. Now we can import that page into a div, so that we can refresh the content of div without reloading the page (or you can create your own JSP page which content may dynamically change). In result, if the database content get change the page will auto refresh to get reload the changes.
For that we have JQuery framework, which you can download from here. And adding the below function of database we can reload the target JSP file in a DIV in every given time interval.

<html>
	<head>
		<Title>Just A Test</Title>
		<script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
        var auto_refresh = setInterval(
        function ()
        {
        $('#load_me').load('showdata.jsp').fadeIn("slow");
        }, 10000); // autorefresh the content of the div after
                   //every 10000 milliseconds(10sec)
        </script>
   </head>
    <body>
    <div id="load_me"> <%@ include file="showdata.jsp" %></div>
    </body>
</html>

Displaying Database Rows in JSP using Java Bean

Last few hours I spend for this solution. I was not getting the exact idea to use ArrayList for an Object, and access methods of that Object from the JSP page. Later I found the solution to be like this, If you have better solution than this please to comment me.

Here is the JavaBean  file were we access the data from the database and merge it to the List allData as objects of Datafields and returning the fields value using getter.



package beans;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ShowDataBean
{
    
    String error;
    List<Object> allData=new ArrayList<Object>();
    
    public String fname,lname,email,password,gender;
    Object obj=new Object();

    public void setObj(Object obj) {
        this.obj = obj;
    }
    public String getError() {
        return error;
    }
    public List getDb_Data()
    {
        int i=0;
        try
        {
                String qry;
                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_eexam","root","root");
                Statement s = con.createStatement();                
                qry="Select fname,lname,email,password,gender from tbl_user_primary";
                ResultSet r=s.executeQuery(qry);
                while(r.next())
                {
                    DataFields d=new DataFields(r.getString(1), r.getString(2), r.getString(3),r.getString(4), r.getString(5));                    
                    allData.add(i,d);
                    i++;
                }
                
        }
        catch(Exception ex)
        {
                error="<b>Contact Administrator :</b><br/>" + ex;
                System.out.println("Your query is not working" + ex);
        }
       return allData;
    }
    public String getFname()
    {
        this.fname=((DataFields)obj).fname;
        return this.fname;
    }
    public String getEmail() {
        this.email=((DataFields)obj).email;
        return this.email;
    }

    public String getGender() {
        this.gender=((DataFields)obj).gender;
        return this.gender;
    }
    public String getLname() {
        this.lname=((DataFields)obj).lname;
        return this.lname;
    }
    public String getPassword() {
        this.password=((DataFields)obj).password;
        return this.password;
    }

    public class DataFields
    {
        public String fname,lname,email,password,gender;

        public DataFields(String  fname,String  lname,String  email,String  password,String  gender)
        {
            this.fname=fname;
            this.lname=lname;
            this.email=email;
            this.password=password;
            this.gender=gender;
        }
    }
   
}

In JSP file we are accessing (getting) the fields after setting the object that is stored in each index of the List.


<%@ page import="java.util.*" %>
<jsp:useBean id="showDataBean" class="beans.ShowDataBean" scope="request" />

<table width="900" cellspacing="0" cellpadding="0">
    <tr>
  
        <td>
        Name
        </td>
        <td>
        Email
        </td>
        <td>
        PassWord
        </td>
        <td>
        Gender
        </td>
       
    </tr>
    <%
		List<Object> list=new ArrayList<Object>();
		list=showDataBean.getDb_Data();
		for(int i=0;i<list.size();i++)
        {
			showDataBean.setObj(list.get(i));
		%>
        
    <tr>
        <td>
        <%
			out.print(showDataBean.getFname() +" "+ showDataBean.getLname());
		
		%>
        </td>
        <td>
        <%
			out.print(showDataBean.getEmail());
		%>
        </td>
        <td>
        <%
			out.print(showDataBean.getPassword());
		%>
        </td>
        <td>
       <%
			out.print(showDataBean.getGender());
		%>
        </td>
		
    </tr>
    <% }%>
</table>