Monday, 25 March 2013

ProgrammingFree's Montage Page

I just created a page for my blog in Microsoft's Montage. For those who do not know what Montage is, it is a web-based service released in 2010 that comes from Fuse, a research-focused division of Microsoft that concentrates on social, real-time and rich media experiences. From CNET.com - "Montage lets you pick content from several sources, including news stories, RSS Feeds, Twitter timelines, images, and YouTube videos. You can even add your own text to a section. Each section then links to the original news source so you can read the full story. The content in each section can remain static by pointing to specific news stores or change dynamically by pointing to Twitter feeds.Once you've finished designing your page, you can save it to your own "My Montage" page, publish it to the public Montage gallery, and share it via Facebook or Twitter. You can also search for and browse pages created by other people at the gallery."

Below is the screenshot of the page I create at Montage showcasing some of the popular post from this blog, 



Create your own montage, share it with your friends and have fun. I will be updating this Montage with my latest posts. So do not forget to bookmark this montage and share it with your friends.

                                                

Sunday, 10 March 2013

AJAX Fetch Data from Database in JSP and Servlet with JSONArray

I had previously written two posts about implementing AJAX in Java web applications. One is about making ajax calls to Servlet & update JSP page with response using jQuery and the other is about implementing cascading dropdownlists in AJAX using JSON and jQuery. One more scenario where AJAX implementation is much desirable is while fetching data from database. So in this post, I am going to explain on how to fetch data from MySql database in JSP and Servlet with JSON and jQuery.


AJAX Fetch Data from Database in JSP and Servlet using jQuery | programming-free.com



In one of my posts, I wrote about what is JSON and how it can be used to convert complex Java Objects like lists, maps, arrays to Javascript Strings that can be parsed using jQuery. To fetch number of rows containing data from database, multiple JSON objects should be returned from Servlet using JSONArray. There are many JSON libraries available and I am going to use google's gson library in this example. 

1. First step is to download all required libraries,


2. Create a Web Application and add the downloaded jar files to WEB-INF/lib folder.

3. Create a model class that represents structure of data in your database table. In this example, I am using mysql country table with the following structure,

-------------------------+------+-----+---------+-------+
| Field          | Type  | Null | Key | Default | Extra |
-------------------------+------+-----+---------+-------+
| Code           | char(3)| NO  | PRI |         |       |
| Name           | char(52)| NO |     |         |       |
| Continent      | char(100)| NO|     | Asia    |       |
| Region         | char(26)| NO |     |         |       |
| Population     | int(11) | NO |     | 0       |       |
| Capital        | int(11)| YES |     | NULL    |       |


I suggest you to create a table with the same structure. Create a class and name it as "Countries.java". Copy and paste the below code in it.

public class Countries {
 
 public Countries(String code,String name, String continent,String region,int population, String capital )
        {      
          this.setCode(code);
          this.setName(name);
          this.setContinent(continent);
          this.setRegion(region);
          this.setPopulation(population);
          this.setCapital(capital);
        }
 
 public Countries() {
  
 }

    private String code;
    private String name;
    private String continent;
    private String region;
    private int population;   
    private String capital;
    
      
    public void setCode(String code) {
  this.code = code;
 }
 public String getCode() {
  return code;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getName() {
  return name;
 }

 public void setContinent(String continent) {
  this.continent = continent;
 }

 public String getContinent() {
  return continent;
 }

 public void setRegion(String region) {
  this.region = region;
 }

 public String getRegion() {
  return region;
 }

 
 public void setPopulation(int population) {
  this.population = population;
 }

 public int getPopulation() {
  return population;
 }

 
 public void setCapital(String capital) {
  this.capital = capital;
 }

 public String getCapital() {
  return capital;
 }
}

4. Create a class and name it as 'FetchData.java'. Copy and paste the below code. This class contains code to connect to database and retrieve values from it.

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;


public class FetchData {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null)
            return connection;
        else {
            try {
                Properties prop = new Properties();
                InputStream inputStream = FetchData.class.getClassLoader().getResourceAsStream("/db.properties");
                prop.load(inputStream);
                String driver = prop.getProperty("driver");
                String url = prop.getProperty("url");
                String user = prop.getProperty("user");
                String password = prop.getProperty("password");
                Class.forName(driver);
                connection = DriverManager.getConnection(url, user, password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return connection;
        }

    }
    
    public static ArrayList<Countries> getAllCountries() {
     connection = FetchData.getConnection();
        ArrayList<Countries> countryList = new ArrayList<Countries>();
        try {
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery("select * from country limit 10");
        
            while(rs.next()) { 
             Countries country=new Countries();
             country.setCode(rs.getString("Code"));
             country.setName(rs.getString("Name"));
                country.setContinent(rs.getString("Continent"));
                country.setRegion(rs.getString("Region"));
             country.setPopulation(rs.getInt("Population"));
             country.setCapital(rs.getString("Capital"));
             countryList.add(country);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return countryList;
    }
}

I have created a file under src folder to store mysql database connection string properties in the name "db.properties" and retrieving values from it. Below is the contents of db.properties file.


driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/dbname
user=root
password=xxxxxx


5. Create a Servlet and name it as 'PopulateTable'. Copy and paste the below code. The below code retrieves data from mysql table using getAllCountries() method of FetchData class and sends JSONArray object as response.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;


@WebServlet("/PopulateTable")
public class PopulateTable extends HttpServlet {
 private static final long serialVersionUID = 1L;

    public PopulateTable() {
        
    }
 
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
  ArrayList<Countries> country=new ArrayList<Countries>();
  country=FetchData.getAllCountries();
  Gson gson = new Gson();
  JsonElement element = gson.toJsonTree(country, new TypeToken<List<Countries>>() {}.getType());

  JsonArray jsonArray = element.getAsJsonArray();
  response.setContentType("application/json");
  response.getWriter().print(jsonArray);
  
 }

 
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
 }

}

Note in the above code, a gson object is invoked and then the 'country' ArrayList object of type "Countries" that contains data populated from database is serialized using toJsonTree(object,Type) method. Then this JSONElement object is converted to JSONArray and passed to the reponse object. More details on serializing data using GSON can be found here.


6. Finally create JSP page and copy paste below html code in it.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX JsonArray Example</title>
<link href='http://fonts.googleapis.com/css?family=Oxygen' rel='stylesheet' type='text/css'>
<style type="text/css">
table, td, th
{
border:1px solid green;
font-family: 'Oxygen', sans-serif;
}
th
{
background-color:green;
color:white;
}
body
{
 text-align: center;
}
.container
{
 margin-left: auto;
 margin-right: auto;
 width: 40em;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $("#tablediv").hide();
     $("#showTable").click(function(event){
           $.get('PopulateTable',function(responseJson) {
            if(responseJson!=null){
                $("#countrytable").find("tr:gt(0)").remove();
                var table1 = $("#countrytable");
                $.each(responseJson, function(key,value) { 
                     var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
                        rowNew.children().eq(0).text(value['code']); 
                        rowNew.children().eq(1).text(value['name']); 
                        rowNew.children().eq(2).text(value['continent']); 
                        rowNew.children().eq(3).text(value['region']); 
                        rowNew.children().eq(4).text(value['population']); 
                        rowNew.children().eq(5).text(value['capital']); 
                        rowNew.appendTo(table1);
                });
                }
            });
            $("#tablediv").show();          
  });      
});
</script>
</head>
<body class="container">
<h1>AJAX Retrieve Data from Database in Servlet and JSP using JSONArray</h1>
<input type="button" value="Show Table" id="showTable"/>
<div id="tablediv">
<table cellspacing="0" id="countrytable"> 
    <tr> 
        <th scope="col">Code</th> 
        <th scope="col">Name</th> 
        <th scope="col">Continent</th> 
        <th scope="col">Region</th> 
        <th scope="col">Population</th> 
        <th scope="col">Capital</th>          
    </tr> 
</table>
</div>
</body>
</html>

That is all! Let me explain what the above code does. I have a button "Show Table" and when the user clicks on it, it does a partial page update and displays a table with values populated from database. 

The jQuery script is the heart of this code, initially I am hiding the table on page load and when the user clicks on "Show Table" button, the first step is to clear the existing rows of the table, if any. Then an AJAX call is made to the Servlet "PopulateTable" using $.get jQuery method and  response from the servlet is received in the 'responseJson' object which is a JSONArray object. After this, response JSONArray is parsed by looping through each of its row and a new table row is created for every JSONArray record. All the new rows that are created is then appended to the table, "countrytable" and is displayed in the page.

Initially when the page loads, the page looks like this,

AJAX Fetch Data from Database in JSP and Servlet using jQuery | programming-free.com

When 'Show Table' button is clicked, partial page update occurs and the table with data is displayed as shown below,


AJAX Fetch Data from Database in JSP and Servlet using jQuery | programming-free.com


                        Download Source


Updates:

Check out these posts that are written on the same topic for know more about AJAX in Java Web Applications,



Please leave your comments and views about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts.

Sunday, 3 March 2013

ASP.NET : Freeze GridView Header using GridViewScroll jQuery plugin

When you have lots of rows to be displayed in a gridview say for example 500 records, if an user is interested in seeing 400th record, the user has to scroll all the way down through the page, if there is no paging or scrolling functionality. Also when gridview is made scrollable, headers will also scroll along with the other gridview contents making it difficult for the user to understand the data properly. There are many javascript and css solutions to freeze gridview header, but each of them has its own drawback like some solutions are not compatible with all browsers, some does not get aligned properly and some does not support other gridview features such as paging and sorting. 

Recently, I came across a jQuery plugin called GridViewScroll that enables scrolling in a gridview with fixed headers and is compatible with majority of the browsers. Since this is a client side plugin, this can be used with simple html table also. I used this plugin in one of my real-time applications and found this to be very efficient, since it can be used along with other features of gridview such as paging, sorting and can freeze gridview columns too. We can also use this plugin with Gridview inside AJAX UpdatePanel for other dynamic operations.

Freeze GridView Header using GridViewScroll jQuery Plugin



It is very simple and easy to implement.

1. Download GridViewScroll jQuery plugin from here.

2. Add the css file, jQuery file and images from the download to your ASP.NET project.

3. In your aspx file, use the below code.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Fixed Header GridView</title>   
    <link href="Styles/GridviewScroll.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script> 
    <script src="Scripts/gridviewScroll.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            gridviewScroll();
        });

        function gridviewScroll() {
            $('#<%=GridView1.ClientID%>').gridviewScroll({
                width: 660,
                height: 300,
                startHorizontal:0,
                wheelstep:10,
                barhovercolor:"#3399FF",
                barcolor: "#3399FF"
            });
        } 
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
        <div style="width:670px;margin-left:auto;margin-right:auto;">
        <h2 style="text-align:center;">Freeze/Fixed GridView Header using GridViewScroll jQuery plugin</h2>
        <p style="text-align:center;">Demo by Priya Darshini - Tutorial @ <a href="">Programmingfree</a></p>                     
            <asp:GridView ID="GridView1" runat="server" Width="660px"
                AutoGenerateColumns="false" AllowPaging="false">
            <Columns>
                <asp:BoundField DataField="Code" HeaderText="Code" />
                <asp:BoundField DataField="Name" HeaderText="Name" HeaderStyle-Width="150px" ItemStyle-Width="150px" ItemStyle-CssClass="Wrap" />
                <asp:BoundField DataField="Continent" HeaderText="Continent" />
                <asp:BoundField DataField="Region" HeaderText="Surface Area" />
                <asp:BoundField DataField="Population" HeaderText="Population" />
                <asp:BoundField DataField="IndepYear" HeaderText="Year of Independence" />
                <asp:BoundField DataField="LocalName" HeaderText="Local Name" />
                <asp:BoundField DataField="Capital" HeaderText="Capital" />
                <asp:BoundField DataField="HeadOfState" HeaderText="Head of State" />
                <asp:BoundField DataField="SurfaceArea" HeaderText="Surface Area" />
            </Columns>
            <HeaderStyle CssClass="GridviewScrollHeader" /> 
            <RowStyle CssClass="GridviewScrollItem" /> 
            <PagerStyle CssClass="GridviewScrollPager" /> 
            </asp:GridView>
        </div>  
    </div>    
    </form>    
</body>
</html>

Do not forget to reference jQuery and jQueryUI library in aspx page. In the above code, after page had loaded we are calling gridviewscroll jquery method with all necessary parameters like width and height of gridview.

4. Write code to load gridview with data in code-behind, I have written code to fetch data from mysql database below,
public partial class GridViewScroll : System.Web.UI.Page
    {
        DataTable dt;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //Fetch data from mysql database
                MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;password=xxxxx;database=world; pooling=false;");
                conn.Open();
                string cmd = "select * from country";
                MySqlDataAdapter dAdapter = new MySqlDataAdapter(cmd, conn);
                DataSet ds = new DataSet();
                dAdapter.Fill(ds);
                dt = ds.Tables[0];
                //Bind the fetched data to gridview
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
            catch (MySqlException ex)
            {
                System.Console.Error.Write(ex.Message);

            }              

        }
    }

5. That is all, now build the project. You can see a beautiful gridview with fixed header, horizontal and vertical scroller. Take a look at the live demo here and start using it to create fixed header gridviews.

There are a lot of other things that you can do with GridViewScroll such as freezing columns, header column merge, row hover, cell wrap etc. I hope this post will help you to get started with GridViewScroll.


Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!!

Tuesday, 19 February 2013

ASP.NET: Display GridView Row Details in Modal Popup using Twitter Bootstrap

There are several ways in which you can display details of a gridview row in order for the user to have a quick overview of the complete row. Especially when there are lot of columns in the gridview the user may find it difficult to scroll the page and view the details of entire row. This is why we have a control called 'DetailsView', a data-bound control that can be used to display single record at a time. There are many options to do this such as displaying details in a tooltip on mouseover event using jQuery, using AJAX ModalPopupExtender on click event etc. A more simple yet efficient approach is to display details of a gridview row in a modal popup dialog using Twitter Bootstrap's Modals plugin.



Steps to Follow,

1. Download bootstrap files from here.

2. Include the latest jQuery library, bootstrap files (bootstrap.js,bootstrap.css) from the download and use below html code in .aspx page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Modal Popup using Bootstrap</title>
    <link href="Styles/bootstrap.css" rel="stylesheet" type="text/css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="Scripts/bootstrap.js" type="text/javascript"></script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <div>
            <h2 style="text-align:center;">
                   Display GridView Row Details in Modal Dialog using Twitter Bootstrap</h2>
            <p style="text-align:center;">
                   Demo by Priya Darshini - Tutorial @ <a href="">Programmingfree</a>
            </p>                     
               <asp:GridView ID="GridView1" runat="server" 
                        Width="940px"  HorizontalAlign="Center"
                        OnRowCommand="GridView1_RowCommand" 
                        AutoGenerateColumns="false"   AllowPaging="false"
                        DataKeyNames="Code" 
                        CssClass="table table-hover table-striped">
                <Columns>
                   <asp:ButtonField CommandName="detail" 
                         ControlStyle-CssClass="btn btn-info" ButtonType="Button" 
                         Text="Detail" HeaderText="Detailed View"/>
            <asp:BoundField DataField="Code" HeaderText="Code" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:BoundField DataField="Continent" HeaderText="Continent" />
            <asp:BoundField DataField="Region" HeaderText="Surface Area" />
            <asp:BoundField DataField="Population" HeaderText="Population" />
            <asp:BoundField DataField="IndepYear" HeaderText="Year of Independence" />
            <asp:BoundField DataField="LocalName" HeaderText="Local Name" />
            <asp:BoundField DataField="Capital" HeaderText="Capital" />
            <asp:BoundField DataField="HeadOfState" HeaderText="Head of State" />
               </Columns>
               </asp:GridView>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:UpdateProgress ID="UpdateProgress1" runat="server">
        <ProgressTemplate>
            <br />
        <img src="" alt="Loading.. Please wait!"/>
        </ProgressTemplate>
    </asp:UpdateProgress>
    <div id="currentdetail" class="modal hide fade" 
               tabindex=-1 role="dialog" aria-labelledby="myModalLabel" 
               aria-hidden="true">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" 
                  aria-hidden="true">×</button>
            <h3 id="myModalLabel">Detailed View</h3>
       </div>
   <div class="modal-body">
        <asp:UpdatePanel ID="UpdatePanel2" runat="server">
            <ContentTemplate>
                    <asp:DetailsView ID="DetailsView1" runat="server" 
                              CssClass="table table-bordered table-hover" 
                               BackColor="White" ForeColor="Black"
                               FieldHeaderStyle-Wrap="false" 
                               FieldHeaderStyle-Font-Bold="true"  
                               FieldHeaderStyle-BackColor="LavenderBlush" 
                               FieldHeaderStyle-ForeColor="Black"
                               BorderStyle="Groove" AutoGenerateRows="False">
                        <Fields>
                 <asp:BoundField DataField="Code" HeaderText="Code" />
                 <asp:BoundField DataField="Name" HeaderText="Name" />
                 <asp:BoundField DataField="Continent" HeaderText="Continent" />
                 <asp:BoundField DataField="Region" HeaderText="Surface Area" />
                 <asp:BoundField DataField="Population" HeaderText="Population" />
                 <asp:BoundField DataField="IndepYear" HeaderText="Year of Independence" />
                 <asp:BoundField DataField="LocalName" HeaderText="Local Name" />
                 <asp:BoundField DataField="Capital" HeaderText="Capital" />
                 <asp:BoundField DataField="HeadOfState" HeaderText="Head of State" />
                       </Fields>
                  </asp:DetailsView>
           </ContentTemplate>
           <Triggers>
               <asp:AsyncPostBackTrigger ControlID="GridView1"  EventName="RowCommand" />  
           </Triggers>
           </asp:UpdatePanel>
                <div class="modal-footer">
                    <button class="btn btn-info" data-dismiss="modal" 
                            aria-hidden="true">Close</button>
                </div>
            </div>
    </div>
    </div>
    </form>
</body>
</html>

In the above code, I have used a gridview and detailsview. To open detailsview in modal popup on button click, detailsview is placed inside a div with class='modal'.

3. In code-behind page use the below code. Here I am populating gridview with values from mysql table and using linq query to populate detailsview.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;

namespace DetailModalExample
{
    public partial class Default : System.Web.UI.Page
    {
        DataTable dt;
        protected void Page_Load(object sender, EventArgs e)
        {            
                try
                {
                    //Fetch data from mysql database
                    MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;
                         password=priya123;database=world;pooling=false;");
                    conn.Open();
                    string cmd = "select * from country limit 7";
                    MySqlDataAdapter dAdapter = new MySqlDataAdapter(cmd, conn);
                    DataSet ds = new DataSet();
                    dAdapter.Fill(ds);
                    dt=ds.Tables[0];
                    //Bind the fetched data to gridview
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
                catch (MySqlException ex)
                {
                    System.Console.Error.Write(ex.Message);
                
                }                              
        }
   
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if(e.CommandName.Equals("detail"))
            {
                int index = Convert.ToInt32(e.CommandArgument);
                string code = GridView1.DataKeys[index].Value.ToString();
                
                    IEnumerable<DataRow> query = from i in dt.AsEnumerable()
                                      where i.Field<String>("Code").Equals(code)
                                       select i;
                    DataTable detailTable = query.CopyToDataTable<DataRow>();
                    DetailsView1.DataSource = detailTable;
                    DetailsView1.DataBind();
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    sb.Append(@"<script type='text/javascript'>");
                    sb.Append("$('#currentdetail').modal('show');");
                    sb.Append(@"</script>");
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), 
                               "ModalScript", sb.ToString(), false);

            }
        }
    }
}

Note in the above code I am opening the div containing details view in modal popup using single line of jQuery code,

$('#currentdetail').modal('show');

That is all, now clicking the button field in gridview row will open a modal popup that consists of detailsview populated with the corresponding row data. See live demo. (I have created this demo using simple html table and the output will be the same in asp.net page.)


Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!!


Sunday, 17 February 2013

ASP.NET: Responsive GapFree MultiColumn Grids using Nested.js

MultiColumn Dynamic Grid Layouts are very popular nowadays and Pinterest, the fastest growing social network is a familiar real time example of the same. There are many jQuery plugins available for creating such layouts starting from the jQuery Masonry plugin.

Recently, I discovered the existence of a new dynamic grid plugin called Nested developed by Jonas Blomdin that can be used to create a gap free, responsive dynamic grid layout. He had explained clearly how this plugin is different from the established masonry plugin here and that is the reason why I chose the Nested jQuery plugin along with FancyBox jQuery Plugin to create an image portfolio that consists of responsive multicolumn image grids. In this post, I am going to explain how to create responsive multicolumn dynamic grids in ASP.NET using Nested.js plugin.




There are three things that this plugin do,

  • Creates a matrix of all elements and creates a multi column grid.
  • Scans the matrix for gaps and tries to fill them by re-ordering the elements.
  • Resize any element at the bottom of the grid that is bigger (or smaller) than the gap to make the grid completely gap-free.

Steps to follow to implement this,

1. Download Nested jQuery plugin from here.

2. Add the jQuery.nested.js and style.css file from the download to your asp.net project.

3. We are going to display images of varying size using Repeater control. In this scenario, there are two parameters that is required for each grid, one is the value for image source, and the other is the cssclass for each grid.

To understand this let us see how it works in simple html. Each grid item should use css class as explained below,

<div id="container">
  <div class="box size11"></div>
  <div class="box size12"></div>
  <div class="box size21"></div>
  <div class="box size22"></div>
  ...
</div>

Sizing of items are handled by adding sizeWH where W is the number of columns the box shall use and H is the number of rows the box shall use. For example, size12 equals to 1 column and 2 rows, to display an image in this grid, the image should be of 50 X 100 in size.

The base column and row size is set by minWidth option and default is 50. This option can be changed anytime using,

$("#container").nested({minWidth: 100});
To implement the same in asp.net, copy and paste the below code in .aspx file. Make sure you have included the necessary script and css files mentioned in point 1. I have used 27 images in various sizes as explained above to create this portfolio, for example size11 - 50 X 50, size 21- 100 X 50. etc. You can use images or any other content, such as text, buttons and other controls as content for the grid.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Responsive MultiColumn Grid Example</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="jquery.nested.js" type="text/javascript"></script>
    <script type="text/javascript" >
     $(function() {     
       $('#container').nested(); 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="container">
        <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
               <div class="<%#Eval("CssClassVal")%>">
                   <img src="<%# Eval("SmallUrl")%>" alt="" />                   
               </div>            
           </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

4. Use the below code in the code-behind page, here I am building a list that consists of information required for rendering the image such as the size of the image to be supplied to css class, (eg. 11,21.etc) and the path of image to be used by the src attribute. I have stored all images in Images/images_small folder and followed the same naming convention for all the images as in 'img_x.jpg', x starting from 1 to 27.


public class ImageAttributes
    {
        public string SmallUrl { get; set; }
        public string CssClassVal { get; set; }
    }

    public static class PopulateRepeater
    {
        static List<ImageAttributes> objList;
        public static IEnumerable<ImageAttributes> GetData()
        {
            ImageAttributes obj;
            objList = new List<ImageAttributes>();
            //Image size for each image used in the project eg. size53 - 250x150 px
            int[] csssize = new int[]{53,42,34,11,22,45,43,24,37,32,53,23,12,21,23,22,11,
                64,11,12,23,22,11,21,12,11,11};
            for (int i = 1; i <=27; i++)
            {
                obj = new ImageAttributes();
                obj.SmallUrl = String.Format("Images/images_small/img_{0}.jpg",i);                          int size=csssize[i-1];
                obj.CssClassVal = String.Format("box size{0}",size);
                objList.Add(obj);
            }
            return objList;
        }

5. Bind Repeater control with values from PopulateRepeater Class in Page load method as shown below,


     protected void Page_Load(object sender, EventArgs e)
        {
            Repeater1.DataSource = PopulateRepeater.GetData();
            Repeater1.DataBind();
        }

6. That is all, now build the project and open .aspx file in the browser to see the results. Resize browser window to know how the image grids re-align automatically according to the window size.




Caution:

There is a bug in this plug-in that causes the browsers to freeze due to an infinite loop when the viewport is reduced to less than the size of the widest element in the grid. There is a local fix available here. So whenever you use the jquery.nested.js file, make sure you edit the _renderGrid() method in it as mentioned in the issues page.


Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!!



Friday, 15 February 2013

Responsive Table in JSP with Footable.js

I wrote few posts on topics based on responsive design in the recent days. It is always a pain to browse a table in a webpage especially in smaller screens. So once again, in this post I am going to write on how to display a table in JSP with server side pagination that is made to be responsive with Footable.js(a jquery plugin that makes tables in a webpage look great in smaller screens). Simple HTML table demo and explanation of the same can be found here. This is a new plugin developed by Brad Vincent & team, and so far they have added sorting and filtering functionalities to it. 



FooTable is very simple:
  1. It hides certain columns of data at different resolutions (we call these breakpoints).
  2. Rows become expandable to show the data that was hidden.
One disadvantage for now is there is no add-on for pagination which I think is very important for tables with large number of rows. But we can expect an add-on for client side pagination from them in the near future. 

To do server side pagination, I am going to use MySql's SQL_CALC_FOUND_ROWS option. I am not going to explain server side pagination in detail, since responsive table is what I am more concerned here. This is one good article which explains server side pagination in servlet and jsp.

1. First of all create a mysql table with more than five columns and fill it with data.

2. Download Footable jquery plugin from here.

3. Create a Java dynamic web project in Eclipse or in any other IDE that you use and add a new JSP file under WebContent folder. Create folders 'JS' and 'CSS' under web content and add the following files from the Footable download to these folders.

JS - footable-0.1.js
CSS - footable-0.1.css
CSS - 'img' folder from footable download

4. Copy and paste below code in the newly created JSP page.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.PreparedStatement"  %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%!
public int nullIntconv(String str)
{   
    int conv=0;
    if(str==null)
    {
        str="0";
    }
    else if((str.trim()).equals("null"))
    {
        str="0";
    }
    else if(str.equals(""))
    {
        str="0";
    }
    try{
        conv=Integer.parseInt(str);
    }
    catch(Exception e)
    {
    }
    return conv;
}
%>
<%

    Connection conn = null;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","username", "password");

    ResultSet rsFooTable = null;
    ResultSet rsRowCnt = null;
    
    PreparedStatement psFooTable=null;
    PreparedStatement psRowCnt=null;
    
    int iShowRows=10;  // Number of records show on per page
    int iTotalSearchRecords=5;  // Number of pages index shown
    
    int iTotalRows=nullIntconv(request.getParameter("iTotalRows"));
    int iTotalPages=nullIntconv(request.getParameter("iTotalPages"));
    int iPageNo=nullIntconv(request.getParameter("iPageNo"));
    int cPageNo=nullIntconv(request.getParameter("cPageNo"));
    
    int iStartResultNo=0;
    int iEndResultNo=0;
    
    if(iPageNo==0)
    {
        iPageNo=0;
    }
    else{
        iPageNo=Math.abs((iPageNo-1)*iShowRows);
    }
    

    
    String sqlPagination="SELECT SQL_CALC_FOUND_ROWS * FROM country limit "+iPageNo+","+iShowRows+"";

    psFooTable=conn.prepareStatement(sqlPagination);
    rsFooTable=psFooTable.executeQuery();
    
    //// this will count total number of rows
     String sqlRowCnt="SELECT FOUND_ROWS() as cnt";
     psRowCnt=conn.prepareStatement(sqlRowCnt);
     rsRowCnt=psRowCnt.executeQuery();
     
     if(rsRowCnt.next())
      {
         iTotalRows=rsRowCnt.getInt("cnt");
      }
%>
<html>
<head>
<title>Responsive Table in Java Web Application with Footable.js</title>
<meta name="viewport" content = "width = device-width, initial-scale = 1.0, minimum-scale = 1.0, maximum-scale = 1.0, user-scalable = no" />
<link href="css/footable-0.1.css" rel="stylesheet" type="text/css"/>
<!-- Scripts -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script src="js/footable-0.1.js" type="text/javascript"></script>
<script src="js/footable.filter.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
 $('.footable').footable();
});
</script>
</head>
<body>
<h1>Responsive Table in JSP with Footable.js</h1>
<form name="frm">
<input type="hidden" name="iPageNo" value="<%=iPageNo%>">
<input type="hidden" name="cPageNo" value="<%=cPageNo%>">
<input type="hidden" name="iShowRows" value="<%=iShowRows%>">
<table width="100%" class="footable">

<thead>
                  <tr>
                      <th data-class="expand"><u>Code</u></th>
                      <th><u>Name</u></th>
                      <th data-hide="phone"><u>Local Name</u></th>
                      <th data-hide="phone,tablet"><u>Continent</u></th>
                      <th data-hide="phone,tablet"><u>Region</u></th>
                      <th data-hide="phone,tablet"><u>Population</u></th>
                      <th><u>Capital</u></th>
                      <th data-hide="phone,tablet"><u>Year of Independence</u></th>
                      <th data-hide="phone,tablet"><u>Head of State</u></th>
                  </tr>
              </thead>
              <tbody>
<%
  while(rsFooTable.next())
  {
  %>
    <tr>
      <td><%=rsFooTable.getString("code")%></td>
      <td><%=rsFooTable.getString("name")%></td>
      <td><%=rsFooTable.getString("localname")%></td>
       <td><%=rsFooTable.getString("continent")%></td>
       <td><%=rsFooTable.getString("region")%></td>
        <td><%=rsFooTable.getString("population")%></td>
        <td><%=rsFooTable.getString("capital")%></td>
         <td><%=rsFooTable.getString("indepyear")%></td>
         <td><%=rsFooTable.getString("headofstate")%></td>
        
          
    </tr>
    <% 
 }
 %>
 </tbody>
<%
  //// calculate next record start record  and end record 
        try{
            if(iTotalRows<(iPageNo+iShowRows))
            {
                iEndResultNo=iTotalRows;
            }
            else
            {
                iEndResultNo=(iPageNo+iShowRows);
            }
           
            iStartResultNo=(iPageNo+1);
            iTotalPages=((int)(Math.ceil((double)iTotalRows/iShowRows)));
        
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

%>
</table>
<br/>
<table border="1">
<tr>
<td colspan="3">
<div>
<%
        //// index of pages 
        
        int i=0;
        int cPage=0;
        if(iTotalRows!=0)
        {
        cPage=((int)(Math.ceil((double)iEndResultNo/(iTotalSearchRecords*iShowRows))));
        
        int prePageNo=(cPage*iTotalSearchRecords)-((iTotalSearchRecords-1)+iTotalSearchRecords);
        if((cPage*iTotalSearchRecords)-(iTotalSearchRecords)>0)
        {
         %>
          <a href="index.jsp?iPageNo=<%=prePageNo%>&cPageNo=<%=prePageNo%>"> << Previous</a>
         <%
        }
        
        for(i=((cPage*iTotalSearchRecords)-(iTotalSearchRecords-1));i<=(cPage*iTotalSearchRecords);i++)
        {
          if(i==((iPageNo/iShowRows)+1))
          {
          %>
           <a href="index.jsp?iPageNo=<%=i%>" style="cursor:pointer;color: red"><b><%=i%></b></a>
          <%
          }
          else if(i<=iTotalPages)
          {
          %>
           <a href="index.jsp?iPageNo=<%=i%>"><%=i%></a>
          <% 
          }
        }
        if(iTotalPages>iTotalSearchRecords && i<iTotalPages)
        {
         %>
         <a href="index.jsp?iPageNo=<%=i%>&cPageNo=<%=i%>"> >> Next</a> 
         <%
        }
        }
      %>
<b>Rows <%=iStartResultNo%> - <%=iEndResultNo%>   Total Result  <%=iTotalRows%> </b>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
<%
    try{
         if(psFooTable!=null){
          psFooTable.close();
         }
         if(rsFooTable!=null){
          rsFooTable.close();
         }
         
         if(psRowCnt!=null){
             psRowCnt.close();
         }
         if(rsRowCnt!=null){
             rsRowCnt.close();
         }
         
         if(conn!=null){
          conn.close();
         }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
%>

Change database name, username, password in the connection string and table name in the query to match your database.

Note that in the table under thead I have specified which columns to hide initially for phone and tablet views using the data attribute, 'data-hide'. This is one good feature of FooTable that they have made it very intuitive and easy for the developers to implement it  with simple data attributes when compared with the other table plugins like DataTable.

The table is made responsive by adding single line of jQuery,


$(table).footable();

6. That's it we are good to run the jsp file in a server now. I use Tomcat Web server to launch the jsp file. See below screenshots for how table is rendered in different screens,








Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!!

Sunday, 10 February 2013

Image Zoom using jQuery Elevate Zoom Plugin

There are many photo zoom plugins available online that can be used to render images that can be zoomed for a bigger view of parts of the image. This is common now in almost every media related and e-commerce website. One more feature that is being extensively used is the Mac-like lightbox feature which enables you to view the image in its original size in a modal dialog box that floats on top of the browser. These two features can be used at a time on an image using "Elevate jQuery Photo Zoom" plugin that provides support for "FancyBox" (jQuery lightbox library). In this post, I am going to explain how to create image zoom effect and lighbox feature on a gallery of images with Elevate jQuery plugin and FancyBox plugin.




1. First of all download all the required plugins,
2. Copy the following files from the above downloads and place it in your project folder.
  • jquery.fancybox.css
  • jquery.elevateZoom-2.5.3.min.js
  • jquery.fancybox.js
  • jquery.fancybox.pack.js
3. Next step is to set up the images for creating gallery. In this post I have used four images. You have to create three sets of these four images for thumbnail, small and large views. I have used the following dimensions, you can use different set of dimensions as per your requirement.

a. thumbnail - 100 x 67 pixels
b. small - 411 x 274 pixels
c. large - 1280 x 854 pixels

Copy all these images and place it in the project location.

4. Copy and paste the below code in the html file. Make sure you edit the 'src' attribute for all the css and js files that are referenced here to fit to the location of your project folder.

<!DOCTYPE html>
<html>
<head>
 <meta charset='utf-8'/>
 <title>jQuery elevateZoom Demo</title>
 <link href="jquery.fancybox.css" rel="stylesheet" type="text/css" />  
 <script src='http://code.jquery.com/jquery-1.9.1.min.js'></script>
 <script src='jquery.elevateZoom-2.5.3.min.js'></script>
 <script src='jquery.fancybox.js'></script>
 <style type="text/css">
 #gallery_01 img{border:2px solid white;}
 .active img{border:2px solid #333 !important;}
 </style>
</head>
<body style="text-align:center;">
<h1>Image Zoom with FancyBox support using Elevate Zoom Plugin</h1>
<img id="img_01" src="small/image_1.jpg" data-zoom-image="large/image_1.jpg"/>

<div id="gallery_01"> 
  <a href="#" data-image="small/image_1.jpg" data-zoom-image="large/image_1.jpg">
    <img id="img_01" src="thumb/image_1.jpg" />
  </a>
  
  <a href="#" data-image="small/image_2.jpg" data-zoom-image="large/image_2.jpg">
    <img id="img_01" src="thumb/image_2.jpg" />
  </a>

  <a href="#" data-image="small/image_3.jpg" data-zoom-image="large/image_3.jpg">
    <img id="img_01" src="thumb/image_3.jpg" />
  </a>

  <a href="#" data-image="small/image_4.jpg" data-zoom-image="large/image_4.jpg">
    <img id="img_01" src="thumb/image_4.jpg" />
  </a>
</div>

<script>

$("#img_01").elevateZoom({gallery:'gallery_01', cursor: 'pointer', galleryActiveClass: 'active'}); 
//pass the images to Fancybox
$("#img_01").bind("click", function(e) {  
  var ez =   $('#img_01').data('elevateZoom'); 
 $.fancybox(ez.getGalleryList());
  return false;
});

</script>
</body>
</html>

4. That is all you have to do! Now open the html file in browser. Mouse hover the images to see zoom effect as shown below.



Click on the main image to see the image in fancybox as shown below.




Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!!

Responsive Navigation Menu using Twitter Bootstrap

In one of my posts, I gave a brief introduction about Twitter Bootstrap, the latest and most widely used front end framework for responsive web design. It is very easy to create a responsive navigation menu that will automatically turn into dropdownlist for devices with smaller screens with twitter bootstrap. If you are new to responsive web design and you do not want to play around with the CSS media queries yourself, you have landed up on the right page because this post aims at explaining how to create responsive navigation menu on the go with twitter bootstrap.


Responsive navigation menu using twitter bootstrap

View Demo       Download



1. First of all download bootstrap files from here
2. Create an html file and place the 'bootstrap' folder from the download in the same location as this html file. You need 'bootstrap.css','bootstrap.responsive.css' and 'bootstrap.js' files from the download.
3. Copy and paste the below code in the html file you created.

<!DOCTYPE html>
<html>
<head>
 <title>Responsive Menu - ProgrammingFree</title>
<!-- Mobile viewport optimized -->
  <meta name="viewport" content="width=device-width">
<!-- CSS -->
    <link href="bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css" />   
    <link href="bootstrap/css/bootstrap-responsive.css" rel="stylesheet" type="text/css" />
<!--Scripts-->
 <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
 <script src="bootstrap/js/bootstrap.js" type="text/javascript"></script>

</head>
<body>
<div class="container-fluid">
<header>
<h2>Responsive Navigation Menu using Twitter Bootstrap</h2>
<br/>
<div class="row-fluid">
<div class="navbar navbar-inverse">
  <div class="navbar-inner">
    <div class="container-fluid">
  <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
  </a>
  <div class="nav-collapse collapse">
  <ul class="nav">
   <li class="active"><a href="#"><i class="icon-home icon-white"></i> Home</a></li>
   <li><a href="#">Features</a></li>
   <li><a href="">Pricing</a></li>
   <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Products<b class="caret"></b></a>
    <ul class="dropdown-menu">
    <li><a href="#">Latest Products</a></li>
    <li><a href="#">Popular Products</a></li>
    </ul>
   </li>          
   <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Membership<b class="caret"></b></a>
    <ul class="dropdown-menu">
      <li><a href="#">Personal Membership</a></li>
      <li><a href="#">Premium Membership</a></li>
    </ul>
   </li>
   <li><a href="#">Offers</a></li>
   <li><a href="#">Gallery</a></li>
   <li><a href="#">About Us</a></li>
   <li><a href="#">Contact</a></li>
   <li class="dropdown">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown <b class="caret"></b></a>
    <ul class="dropdown-menu">
    <li><a href="#">Action</a></li>
    <li><a href="#">Another action</a></li>
    </ul>
   </li>
        </ul>
    </div><!-- /.nav-collapse -->
    </div><!-- /.container -->
  </div><!-- /.navbar-inner -->
</div><!-- /.navbar -->
<p>Note: Reduce browser window size to see dropdown navigation menu</p>
</div>
</header>
<div>
</body>
</html>

4. That is it! Open the html file in browser you will see navigation menu as shown below,


After re-sizing the browser window, horizontal navigation menu changes to dropdown navigation as shown below,




Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!!

Saturday, 2 February 2013

Gridview in Java Web Applications using jQuery DataTable

In every data driven web application, displaying data in tables is inevitable. In ASP.NET we have Gridview to serve this purpose with many predefined options like paging, sorting, editing etc. But in Java, there is no such control that is just like GridView. JTable from java swing framework can be used in console applications but for web application there is no such inbuilt component. Therefore, the best solution to display data in tables in Java is, to use DataTable, a jQuery plugin that enhances HTML tables in terms of features, look and interactivity. In this post, I am going to explain with example on how to use DataTable plugin to display data in Java web application(JSP page).




Before proceeding to the example, it is good to know the features that DataTable plugin offers to any table,

  • Variable length pagination
  • On-the-fly filtering
  • Multi-column sorting with data type detection
  • Smart handling of column widths
  • Display data from almost any data source
  • Scrolling options for table viewport
  • Fully internationalisable
  • jQuery UI ThemeRoller support
  • Rock solid - backed by a suite of 2900 unit tests
  • Wide variety of plug-ins inc. Editor, TableTools, FixedColumns and more
  • It's free!
In this example, I am going to retrieve values from a csv file and display it in html table. To read the csv file, I am using OpenCSV java library that simplifies the work of parsing CSV files. You can also code to retrieve data from database instead of reading from CSV file. 

1. First of all download all required libraries,
2. Create a dynamic web project in eclipse. Look for opencsv-x.x.jar in the opencsv download folder and add it classpath of the project.

3. Create two folders under YourProject/Webcontent and name it as 'js' and 'css'. Add the following javascript files from DataTable download to the 'js' folder you just created.

  • jquery.dataTables.js
  • jquery.js
Add the following css files  from DataTable download and jquery ui download to 'css' folder.
  • demo_page.css
  • demo_table_jui.css
  • demo_table.css
  • jquery-ui-x.x.x.css
4. Download the csv file from which the data is to be read from here and add it under YourProject/src folder. This css files contains four columns - country,revenue,sales manager,year.

5. Create a new jsp file under WebContent and the folder structure should look like shown below.


6. Now the project setup is done and we can start creating classes to pull data from csv file. First create a model class that gets and sets the data from the four columns - country,revenue,sales manager,year in the csv file. Create a java class under src folder and name it as "SalesReport.java". Copy and paste the below code in SalesReport.java file.

public class SalesReport {

    public SalesReport(String country,String revenue, String salesmanager,String year)
    {      
        this.country = country;
        this.revenue = revenue;
        this.salesmanager = salesmanager;
        this.year=year;
    }
      
    private String country;
    private String revenue;
    private String salesmanager;
    private String year;
  
 public String getCountry() {
  return country;
 }
 
 public String getRevenue() {
  return revenue;
 }
 
 public String getSalesmanager() {
  return salesmanager;
 }
 
 public String getYear() {
  return year;
 }
 
 public void setCountry(String country) {
  this.country = country;
 }
 
 public void setRevenue(String revenue) {
  this.revenue = revenue;
 }
 
 public void setSalesmanager(String salesmanager) {
  this.salesmanager = salesmanager;
 }
 
 public void setYear(String year) {
  this.year = year;
 }
}



7. Next step is to create a class that would fetch data from the csv file using SalesReport model class. Create a class and name it as, "FetchDataFromDb.java". Copy and paste the below the below code in it.



import au.com.bytecode.opencsv.CSVReader;
import SalesReport;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;


public class FetchDataFromDb {
 
 private static List<salesreport> SalesData = null;
 
 public static List<salesreport> GetSalesData() throws IOException{
  
  if(SalesData==null){   
   SalesData=new LinkedList<salesreport>();
   String csvFilename = "country_revenue.csv";
   InputStream is =  Thread.currentThread().getContextClassLoader().getResourceAsStream("com/programmingfree/salesreport/"+csvFilename);
   BufferedReader br = new BufferedReader(new InputStreamReader(is));
   CSVReader csvReader = new CSVReader(br);
   String[] row = null;
   while((row = csvReader.readNext()) != null) {   
      SalesData.add(new SalesReport(row[0],row[1],row[2],row[3]));        
   }      
   csvReader.close();   
  }    
  return SalesData;  
 }    
}


8. Final step is to create jsp file to display the data fetched from csv file in html table and enhance the table with features using DataTable plugin. Copy and paste the below code in the JSP file that is already created for this purpose.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>GridView for Java - jQuery Data Table</title>
<!-- CSS -->
<link href="css/demo_page.css" rel="stylesheet" type="text/css" />
<link href="css/demo_table.css" rel="stylesheet" type="text/css" />       
<link href="css/demo_table_jui.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.8.24.custom.css" rel="stylesheet" type="text/css" media="all" />
<!-- Scripts -->
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.js" type="text/javascript"></script>
 <script type="text/javascript">
        $(document).ready(function () {
            $("#sales").dataTable({
                "sPaginationType": "full_numbers",
                "bJQueryUI": true               
            });
        });
 </script>
</head>
<body id="dt_example">
<div id="container">
<h1>Gridview for Java using jQuery DataTable plugin</h1>
<div id="demo_jui">
<table id="sales" class="display">
              <thead>
                  <tr>
                      <th><u>Country</u></th>
                      <th><u>Revenue</u></th>
                      <th><u>Sales_Manager</u></th>
                      <th><u>Year</u></th>
                  </tr>
              </thead>
              <tbody>
              <% for(SalesReport c: FetchDataFromDb.GetSalesData()){ %>
        <tr>
          <td><%=c.getCountry()%></td>
          <td><%=c.getRevenue()%></td>
          <td><%=c.getSalesmanager()%></td>
          <td><%=c.getYear()%></td>
        </tr>
      <% } %>
              </tbody>
          </table>
          </div>
 </div>
</body>
</html>

That is all. We are done and you will now be able to view a table that is sortable, searchable on all fields with paging features. See screenshot below, the table is searched with the year "2010" and the results are produced accordingly. 






Download source code from above link and import to Eclipse IDE. Run the project on Tomcat server to understand this better. 

Caution
According to the documentation the HTML table should be well formed with <thead> and <tbody> tags like the example given below,

<table id="table_id">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>etc</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row 1 Data 1</td>
            <td>Row 1 Data 2</td>
            <td>etc</td>
        </tr>
        <tr>
            <td>Row 2 Data 1</td>
            <td>Row 2 Data 2</td>
            <td>etc</td>
        </tr>
    </tbody>
</table>


There are many other things you can add to this table like column filteringrow grouping, row editing and more using other plugins that can be used along with dataTable plugin.

Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading!!