Setup and Load Data in jTable using Servlets and JSP

DEMO DOWNLOAD Articles on jTable in Java Web Applications jQuery jTable plugin in Java Web Applications - An Introduction Setup ...





This article is a part of the series of articles written on how to implement AJAX based crud operations and other cool features jTable plugin offers, in Java Web Applications (using Servlets and JSP's - Simple MVC Model 2 Approach). In this post, I am going to explain how to setup jTable and dependant libraries in Java Web Project and display data coming from CSV file. 

1. First of all download all the libraries required for the setup,
jTable offers you several cool themes and you can select the one that will suit your website. jTable uses jQuery UI dialog that pops up when the user clicks on add, edit or update record buttons. If you choose to use any one of the metro themes offered by jTable you can use jQuery UI themeroller to customize it according to the color of the table and then download it. For example, I am going to use 'Crimpson' metro theme here, and therefore I edited and downloaded 'Blitzer' jquery UI theme.

2. Now add necessary files from the download as shown in the project structure below,

3. We are done with the setup. To start with let us try to display an empty table with no data. Create a jsp page under WebContent folder and add below code to it.

index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Setup and Load Data to jTable using Servlets and JSP</title>
<!-- Include one of jTable styles. -->
<link href="css/metro/crimson/jtable.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<!-- Include jTable script file. -->
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="js/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //initialize jTable
        $('#PersonTableContainer').jtable({
            title: 'Table of people',
            actions: {
                listAction: 'CRUDController?action=list',
                createAction:'CRUDController?action=create',
                updateAction: 'CRUDController?action=update',
                deleteAction: 'CRUDController?action=delete'
            },
            fields: {
                customerid: {
                    key: true,
                    list: false
                },
                customername: {
                    title: 'Customer Name',
                    width: '30%'
                },
                email: {
                    title: 'Email',
                    width: '30%'
                },
                phone: {
                    title: 'Phone',
                    width: '20%',
                    create: false,
                    edit: false
                },
                city: {
                    title: 'City',
                    width: '20%',
                    
                }
                
            }
        });        
    });
</script>
</head>
<body>
<div style="width:60%;margin-right:20%;margin-left:20%;text-align:center;">
<h1>Setup and Load Data in jTable using Servlet and JSP</h1>
<h4>Demo by Priya Darshini, Tutorial at www.programming-free.com</h4>
<div id="PersonTableContainer"></div>
</div>
</body>
</html>

When you run the JSP page, you will now see an empty table such as the one shown below, since we have not written server side code to fetch data yet. Note that in the above code we have not written any markup for html table and all we have is a div that acts as a placeholder for the table to be created by the jTable plugin. We have defined an option called 'actions' for the method 'jtable', to provide the action urls for create, delete, update and list server side functions. Another option 'field' defines the field names that represents columns in the data source.


4. Next let us move on to write logic to fetch data from a csv file. The sample csv file I am using here consists of ten records of the following structure,

ID|Customer Name|Email|Phone Number|City

Create a model class, that will have getters and setters for the above fields present in the data source,

Customers.java
package com.programmingfree.model;

public class Customers {

 public Customers(String customerid,String customername,String email,String phone,String city){
  this.customerid=customerid;
  this.customername=customername;
  this.email=email;
  this.phone=phone;
  this.city=city;
 }
 private String customerid;
 private String customername;
 private String email;
 private String phone;
 private String city;
 
 public void setCustomerid(String customerid) {
  this.customerid = customerid;
 }
 public String getCustomerid() {
  return customerid;
 }
 public void setCustomername(String customername) {
  this.customername = customername;
 }
 public String getCustomername() {
  return customername;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public String getEmail() {
  return email;
 }
 public void setPhone(String phone) {
  this.phone = phone;
 }
 public String getPhone() {
  return phone;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getCity() {
  return city;
 }
}

5. Create a data access object class that will do the actual work of getting data from the data source,

DataManipulation.java
package com.programmingfree.dao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;
import com.programmingfree.model.*;

public class DataManipulation {
 
 public static List<Customers> getAllCustomers() throws IOException{
  List<Customers> lstCustomer=new ArrayList<Customers>();
  String csvFilename = "customer.csv";
      InputStream is =  Thread.currentThread().getContextClassLoader().getResourceAsStream(csvFilename);
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      CSVReader csvReader = new CSVReader(br,'|');
      String[] row = null;
      while((row = csvReader.readNext()) != null) {  
         lstCustomer.add(new Customers(row[0],row[1],row[2],row[3],row[4])); 
      }
  return lstCustomer;
 }
}

Note that I have used OpenCsv java library here, that simplifies the job of reading content from source csv file. I have placed the source csv file(customer.csv) under Project/src folder. CsvReader class has a constructor that takes file and delimiter as input and returns a string array.

6. Now let us create a Servlet that acts as a Controller and dispatches request from the view to the Dao class and sends back response to the view.

CRUDController.java
package com.programmingfree.controller;

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;
import com.programmingfree.dao.DataManipulation;
import com.programmingfree.model.Customers;


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

    
    public CRUDController() {
        
    }


 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  if(request.getParameter("action")!=null){
   String action=(String)request.getParameter("action");
   if(action.equals("list")){
    try{
    List<Customers> lstCustomer=new ArrayList<Customers>();
   
    //Fetch Data from CSV file
    lstCustomer=DataManipulation.getAllCustomers();
    
    //Convert Java Object to Json
    Gson gson = new Gson();
    JsonElement element = gson.toJsonTree(lstCustomer, new TypeToken<List<Customers>>() {}.getType());
    JsonArray jsonArray = element.getAsJsonArray();
    String listData=jsonArray.toString();
    
    //Return Json in the format required by jTable plugin
    listData="{\"Result\":\"OK\",\"Records\":"+listData+"}";     
    response.setContentType("application/json");
    response.getWriter().print(listData);
    System.out.println(listData);
    }catch(Exception ex){
     String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace()+"}";
     response.getWriter().print(error);
    }
    
   }
  }
 }

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

}

In the servlet, we are populating a list of type "Customers"(Model) using getAllCustomers() static method that we defined previously in the DataManipulation class. Then we are converting this List (Java Object) to Json(Javascript object Notation) format using Google json library. Note that jTable accepts data only in Json format and all crud based actions those are used by jTable should return json in the format as in the following sample,

{
 "Result":"OK",
 "Records":[
  {"PersonId":1,"Name":"Benjamin Button","Age":17,"RecordDate":"\/Date(1320259705710)\/"},
  {"PersonId":2,"Name":"Douglas Adams","Age":42,"RecordDate":"\/Date(1320259705710)\/"},
  {"PersonId":3,"Name":"Isaac Asimov","Age":26,"RecordDate":"\/Date(1320259705710)\/"},
  {"PersonId":4,"Name":"Thomas More","Age":65,"RecordDate":"\/Date(1320259705710)\/"}
 ]
}


Result property can be "OK" or "ERROR". If it is "OK", Records property must be an array of records. If it is "ERROR", a Message property can explain reason of the error to show to the user.

7. Edit web.xml file to create servlet mapping for our Controller servlet to work with the url pattern '/CRUDController'.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>jTableJavaExample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
<servlet>
    <servlet-name>CRUDController</servlet-name>
    <servlet-class>com.programmingfree.controller.CRUDController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>CRUDController</servlet-name>
    <url-pattern>/CRUDController</url-pattern>
</servlet-mapping>
</web-app>

8. Finally we have to call the 'load' method in the jsp page that we created before. We just initialized it before. For the JSP to fire AJAX call to server listaction method 'load' method needs to be called after table initialization code as shown below,

index.jsp
<script type="text/javascript">
    $(document).ready(function () {
        $('#PersonTableContainer').jtable({
            title: 'Table of people',
            actions: {
                listAction: 'CRUDController?action=list',
                createAction:'CRUDController?action=create',
                updateAction: 'CRUDController?action=update',
                deleteAction: 'CRUDController?action=delete'
            },
            fields: {
                customerid: {
                    key: true,
                    list: false
                },
                customername: {
                    title: 'Customer Name',
                    width: '30%'
                },
                email: {
                    title: 'Email',
                    width: '30%'
                },
                phone: {
                    title: 'Phone',
                    width: '20%',
                    create: false,
                    edit: false
                },
                city: {
                    title: 'City',
                    width: '20%',
                    
                }
                
            }
        });
        $('#PersonTableContainer').jtable('load');
    });
</script>

Note that we have implemented server side logic only to load table with data and we have not yet handled create, update and delete operations. I will update the code for AJAX based crud operations in my next article.

That is all! We are good to run the application to see data loaded from CSV file 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!!

Subscribe to GET LATEST ARTICLES!


Related

jTable 2619437573149789941

Post a Comment

  1. Realy I love this..thank u very much for sharing this.....

    ReplyDelete
  2. hey priya, it was really very good tutorial, can you please help me exporting this project in netbeans, i never used eclipse. :( Please.

    email: dtiwari18@gmail.com

    ReplyDelete
    Replies
    1. Hi,

      You can try this,

      https://netbeans.org/kb/docs/java/import-eclipse.html

      Hope this helps!

      Thanks,
      Priya

      Delete
  3. Good, but what if I need more complex fields than simple strings? Put the case I have a list of customers, which have some properties and foreign keys which points to other objects.
    Is it possible to build the form which edits/creates the records of the table?
    Thanks

    ReplyDelete
  4. Thanks for the great tutorial. Could you be having an example of CRUD with twitter bootstrap and servlets?

    ReplyDelete
  5. Great tutorial...this save my days..Thanks alot..=)

    ReplyDelete
  6. My json response looks like below and it doesn't work

    {"records":[{"Desc":"APPLICATION FORM","ctrlId":2,"ctrlName":"SSN Application"}],
    "result":"OK"}

    ReplyDelete
    Replies
    1. Looks like the property names are case sensitive. Only "Result" and "Records" will work.
      I'm using struts and the "result" is becoming all lower case "result"in the json response.

      I edited the jtable.js to replace Result to result and Records to records then it worked.

      Delete
    2. Hi sahoo,

      Glad that you got it working finally :) You can also have a request placed at jtable.org to add your fix so others who use struts might take advantage of your solution. Thank you so much for the information and I appreciate your effort to take some time and post it here.

      Thanks,
      Priya

      Delete
  7. I got around the problem using another way.
    On the pojo class that I'm using for the data record, I use @JASON(name="Record"), to force the JSON handler to use the custom name instead of the default and that did the trick.

    ReplyDelete
  8. Hi how to implement paging in this jtable.I am not clear about actually what to return from servlet to json to implement page in this jtable

    ReplyDelete
    Replies
    1. Did you check this?

      http://www.programming-free.com/2014/02/jtable-pagination-in-java-web.html

      Delete
  9. Hi Priya, greetings from México. How I can customize messages of jTable to Spanish?

    ReplyDelete
    Replies
    1. Hi,

      The latest version of jTable (v 2.3.1) has an option to localize jTable messages.

      http://jtable.org/Demo/TurkishLocalization

      Hope this helps!

      Delete
  10. Hi, very good tutorial but i have a little issue, I'm trying to follow all the steps using NetBeans but the interaction between jsp and servlet doesn't happen, I've tried to fix the file web.xml but it still doing nothing.

    I'd really appreciated some help. Thank you

    ReplyDelete
  11. Hi Priya,
    The document is really Excellent !!!. I extend my sincer thanks for uploading the same for new developer like me and it will help us to upgrade our knowledge.
    I am trying to do the exact replica in my system. The web site unable to launch as it is giving runtime error. The issue is with @WebServlet. The system is giving run time error like "Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)". I am unable to fix the issue. Can you please throw some lite and help if you please?

    Regards Milind

    ReplyDelete
    Replies
    1. Hi,

      We have used deployment descriptor (web.xml) in this application. @WebServlet is an annotation that is meant to replace deployment descriptor. So, you can safely remove this annotation from your servlet. Do not have both web.xml and @WebServlet annotation at the same time.

      Hope this helps!

      Thanks,
      Priya

      Delete
  12. Hi Priya,
    Awesome article and code. Can you please tell us how can we configure the colors used in the grid and also the size of the grid.

    ReplyDelete
  13. how we can validate jtable feilds...please help

    ReplyDelete
    Replies
    1. Hi,

      You can use jquery validation plugin. Check this out.

      http://www.jtable.org/Demo/UsingWithValidationEngine1

      Thanks,
      Priya

      Delete
  14. Hi Priya,

    Great tutorial. My question is how do I force format field in jTable that stores XML data strings? The viewing browser ignores the tags and will not display the table content properly. Any help is greatly appreciated-

    Thanks,
    JC

    ReplyDelete
  15. Hey Hello priya,
    Can u give me an example which shows the different images on index page n after selecting a particular image it should show the black and white pixels from that image n the size of image but on the same page(ajax).Can u please help me.?
    my id - deshmukhmayuri@hotmail.com

    ReplyDelete
  16. How do i include the add new record button at the top of the table

    ReplyDelete
  17. Hi Priya
    I am not be able to code for options: '/Demo/GetCityOptions' action to work with struts 2, kind send the action code in java for populating data in combo box for adding and editing records

    Vipin

    ReplyDelete
  18. Hi Priya this is awesome , but iam trying every step and i did it all , and i downloaded the demo and still doesn't working , can u help me please , i really need this .
    thank u

    ReplyDelete
  19. I am unable to override server error message ("An error occured while communicating to the server.") to my custom error message in my application. i am currently using struts 1.3 (
    String message = "Exception: my custom";
    String error = "{\"Result\":\"ERROR\",\"Message\":"+message+ "}";
    response.getWriter().print(error);)

    always showing error - An error occured while communicating to the server.
    Could you please on this. i have to override my current error to view end user.

    Thanks
    Ramanujadasu

    ReplyDelete
  20. Hello Priya,
    I am unable to load data through server to jsp page using jtable.
    When I try to run the things in the debug mode, I found that call to the servlet is not being made & I get the error dialog as Error Occurred While Communing with the server.

    My structure is Web Content->Pages->test.jsp. Js pages are include by the following relative path ../Js/*.js
    Web Content->Js (where all js pages are stored)

    But the interesting thing is that when I copy paste the same jsp file in the Web Content folder & change the path of the js file(Js/*.js) all works fine even data is being populated in the jtable.

    Can you please help me to resolve this thing. I am not able to understand this thing ( If jsp file is present inside the Web Content-> Pages folder servlet call not being made)

    Thanks in advance

    ReplyDelete
  21. I am unable to run this application on Tomcat server on Eclipse. Reply

    ReplyDelete
  22. Hello Priya,
    In your tutorial, you directly write out to response. Can I use forward to another jsp instead? My code is as below:
    listData="{\"Result\":\"OK\",\"Records\":"+listData+"}";
    response.getWriter().write(listData);

    RequestDispatcher dispatcher = request.getRequestDispatcher("test.jsp");
    dispatcher.forward(request, response);
    Thanks in advance

    ReplyDelete
  23. Hi,
    Do you know where I can download this example? The download link above is not working.
    Thanks

    ReplyDelete
  24. Hi Priya,

    How can I put select options instead of data field? How can I convert this to java?


    var countries = _repository.CountryRepository.GetAllCountries(continentalId).Select(c => new { DisplayText = c.CountryName, Value = c.CountryId }).OrderBy(s => s.DisplayText);


    Thanks!

    ReplyDelete
  25. Hello, does anyone know how to change the layout of Edit and Create HTML of JTable framework ?

    ReplyDelete
  26. Good, but what if I need more complex fields than simple strings or Int? Put the case I have a list of customers, which have some properties and foreign keys which points to other objects.
    Is it possible to build the form which edits/creates the records of the table?
    e.g
    public class Myclass
    {
    String name;
    student stu;
    int number;

    }

    student has two fields{
    int stuId;
    string StuName;
    }


    Here How can i put that student type fields in my MYCLASS jtable representation ,,
    is there any need to iterate it>???????
    Thanks

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. This comment has been removed by the author.

    ReplyDelete
  29. Hello, how to bind using a managed bean for an xhtml JSF webapp, example:





    Number
    #{u.caseno}



    ReplyDelete
  30. Nice tutorial. The ads on your blog sometimes cause this page to reload endlessly, causing the page to freeze during scrolling on Chrome.

    ReplyDelete
  31. Hi,
    Thanks for the tutorial, but I'am getting a empty table without any records, it is printing exact number of rows as in the database, but the table is empty. Data prints correctly when printed using system.out. Please help me resolve this Problem,
    Thanks in advance.

    ReplyDelete
  32. Really useful information. Thank you so much for sharing.It will help everyone.Keep Post. RPA training in chennai | RPA training in Chennai with placement

    ReplyDelete
  33. Outstanding blog thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us.
    best training insitute for machine learning
    machine learning classroom training in chennai
    machine learning with python course in chennai
    best machine learning institutes in chennai

    ReplyDelete
  34. Hello, I read your blog occasionally, and I own a similar one, and I was just wondering if you get a lot of spam remarks? If so how do you stop it, any plugin or anything you can advise? I get so much lately it’s driving me insane, so any assistance is very much appreciated.
    Android Course Training in Chennai | Best Android Training in Chennai
    Datascience Course Training in Chennai | Best Data Science Training in Chennai

    ReplyDelete
  35. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.

    Check out : hadoop training in chennai cost
    hadoop certification training in chennai
    big data hadoop course in chennai with placement
    big data certification in chennai

    ReplyDelete
  36. How to implement selected single rows with color using jtable in MVC?
    e.g - Display the selected login user in the user list model page.

    ReplyDelete
  37. Interesting information and attractive.This blog is really rocking... Yes, the post is very interesting and I really like it.I never seen articles like this. I meant it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job.
    Kindly visit us @
    Sathya Online Shopping
    Online AC Price | Air Conditioner Online | AC Offers Online | AC Online Shopping
    Inverter AC | Best Inverter AC | Inverter Split AC
    Buy Split AC Online | Best Split AC | Split AC Online
    LED TV Sale | Buy LED TV Online | Smart LED TV | LED TV Price
    Laptop Price | Laptops for Sale | Buy Laptop | Buy Laptop Online
    Full HD TV Price | LED HD TV Price
    Buy Ultra HD TV | Buy Ultra HD TV Online
    Buy Mobile Online | Buy Smartphone Online in India

    ReplyDelete
  38. Thanks for sharing such a Wonderful blog. This is such a exact information i am been searching for. Keep post

    Check Out:
    react js tutorial
    it courses in chennai
    react js classes near me

    ReplyDelete
  39. It’s interesting content and Great work. Definitely, it will be helpful for others. I would like to follow your blog. Keep post

    Check out:
    Selenium training courses in chennai
    Selenium training center in chennai
    Selenium training in chennai quora
    Selenium course fees in chennai

    ReplyDelete
  40. Thanks a lot..it was really helpful...

    ReplyDelete
  41. Many interesting stuff here. Keep posting. Also check Mit Sat Requirements 2021

    ReplyDelete
  42. Sandeep maheshwari win 80,000 Rupees in goa 온라인현금바둑이 사설바둑이사이트 모바일바둑이

    ReplyDelete
  43. Thank you for sharing such informative content! I found it to be incredibly useful and learned a lot from it. Keep up the great work and looking forward to reading more from you in the future.

    Defi Development Company

    ReplyDelete

emo-but-icon

SUBSCRIBE


item