CRUD Operations in Java Web Applications using jTable jQuery plugin

DEMO DOWNLOAD This post is a part of the series of articles on using jQuery jTable in Java Web Applications. In my previous po...





This post is a part of the series of articles on using jQuery jTable in Java Web Applications. In my previous post I explained how to setup jTable and how to get data from server side to display in jTable. Now let us see how to use jTable jQuery plugin to perform AJAX based CRUD operations in Java Web Applications (using MySql Server and Model 2 Approach with JSP, Servlets and POJO's).

1. First let us create an user table with the following simple query in MySql Server and enter some dummy records in it.

create table tblUser(userid int,firstname varchar(50),lastname varchar(50),email varchar(50)); 

2. Next step is to create a dynamic web project in eclipse and setup all required libraries in it. I have explained how to download and setup jTable in Java Web Project here   

In addition to that, we need to add MySql Java Connector jar file to Project Location/WEB-INF/lib folder.

3. Now let us create a model class('User.java') that contains getters and setters for the fields we have in mySql table. 

package com.programmingfree.model;

 public class User {

  private int userid;
  private String firstName;
  private String lastName; 
  private String email;
  
  public int getUserid() {
   return userid;
  }
  public void setUserid(int userid) {
   this.userid = userid;
  }
  public String getFirstName() {
   return firstName;
  }
  public void setFirstName(String firstName) {
   this.firstName = firstName;
  }
  public String getLastName() {
   return lastName;
  }
  public void setLastName(String lastName) {
   this.lastName = lastName;
  }
  
  
  public String getEmail() {
   return email;
  }
  public void setEmail(String email) {
   this.email = email;
  }
  @Override
  public String toString() {
   return "User [userid=" + userid + ", firstName=" + firstName
     + ", lastName=" + lastName + ", email="
     + email + "]";
  }
  
  
 }

4. Next let us create a utility class to handle connections to database. The connection string properties are kept in a configuration file called "config.properties" in the src folder.
package com.programmingfree.utility;

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


public class DBUtility {
 private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null)
            return connection;
        else {
            try {
             Properties prop = new Properties();
                InputStream inputStream = DBUtility.class.getClassLoader().getResourceAsStream("/config.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;
        }

    }

}


Properties configuration file should have contents such as this, 

driver=com.mysql.jdbc.Driver 
url=jdbc:mysql://localhost:3306/databasename 
user=username 
password=xxxxxx 

5. Next step is to create a class that performs database operations such as select, create, delete and update. 
package com.programmingfree.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.programmingfree.model.User;
import com.programmingfree.utility.DBUtility;
public class CrudDao {
 
 private Connection connection;

 public CrudDao() {
  connection = DBUtility.getConnection();
 }

 public void addUser(User user) {
  try {
   
   PreparedStatement preparedStatement = connection
     .prepareStatement("insert into tblUser(userid,firstname,lastname,email) values (?,?, ?, ? )");
   // Parameters start with 1
   preparedStatement.setInt(1, user.getUserid());
   preparedStatement.setString(2, user.getFirstName());
   preparedStatement.setString(3, user.getLastName());   
   preparedStatement.setString(4, user.getEmail());
   preparedStatement.executeUpdate();

  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
 
 public void deleteUser(int userId) {
  try {
   PreparedStatement preparedStatement = connection
     .prepareStatement("delete from tblUser where userid=?");
   // Parameters start with 1
   preparedStatement.setInt(1, userId);
   preparedStatement.executeUpdate();
  } catch (SQLException e) {
   e.printStackTrace();
  }
 }
 
 public void updateUser(User user) throws ParseException {
  try {
   PreparedStatement preparedStatement = connection
     .prepareStatement("update tblUser set lastname=?,email=?" +
       "where userid=?");
   // Parameters start with 1   
   preparedStatement.setString(1, user.getLastName());
   preparedStatement.setString(2, user.getEmail());   
   preparedStatement.setInt(3, user.getUserid());
   preparedStatement.executeUpdate();

  } catch (SQLException e) {
   e.printStackTrace();
  }
 }

 public List<User> getAllUsers() {
  List<User> users = new ArrayList<User>();
  try {
   Statement statement = connection.createStatement();
   ResultSet rs = statement.executeQuery("select * from tblUser");
   while (rs.next()) {
    User user = new User();
    user.setUserid(rs.getInt("userid"));
    user.setFirstName(rs.getString("firstname"));
    user.setLastName(rs.getString("lastname"));    
    user.setEmail(rs.getString("email"));
    users.add(user);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }

  return users;
 }
 
 public User getUserById(int userId) {
  User user = new User();
  try {
   PreparedStatement preparedStatement = connection.
     prepareStatement("select * from tblUser where userid=?");
   preparedStatement.setInt(1, userId);
   ResultSet rs = preparedStatement.executeQuery();
   
   if (rs.next()) {
    user.setUserid(rs.getInt("userid"));
    user.setFirstName(rs.getString("firstname"));
    user.setLastName(rs.getString("lastname"));
    
    user.setEmail(rs.getString("email"));
   }
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return user;
 }

}

6. Now it is the right time to create controller servlet that would call the data access methods to perform real CRUD operations. But before that, let us see what kind of response jTable jQuery plugin expects for each type of operation. This is important because jTable will work as expected only when we provide response in the proper format as expected by the plugin. 

All CRUD operations must return response in JSON format. Following are the examples of responses to be sent to jTable for each type of operation,

CREATE RECORD

For create operations, the response from server side must return newly created record (as JSON object)! sample return value for createAction can be:

{
 "Result":"OK",
 "Record":{"PersonId":5,"Name":"Dan Brown","Age":55,"RecordDate":"\/Date(1320262185197)\/"}
}

The returning JSON object must contain a Result property that's value can be "OK" or "ERROR". If it's "OK",Record property is the created record. 

LIST RECORDS (READ OPERATION)

For read operations, 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.

{
 "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)\/"}
 ]
}

Heads Up!! - Note for listing records the response should be a JSON Array and not simple JSON Object whereas for create operations it is the opposite of it, should return JSON object and not a JSON Array. Also, for create operation the second parameter in the JSON Response is "Record" and for list operations it is "Records" in plural.

UPDATE & DELETE RECORD

For update and delete operations, server side response is very simple with Result parameter alone such as this,

{"Result":"OK"}

Let us now go ahead and create controller servlet that receives request from JSP, dispatches request to underlying POJO and then send back response to JSP in JSON format as explained above.
package com.programmingfree.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
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.CrudDao;
import com.programmingfree.model.User;


public class CRUDController extends HttpServlet {
 private static final long serialVersionUID = 1L;
 private CrudDao dao;
    
    public CRUDController() {
        dao=new CrudDao();
    }


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

 
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  if(request.getParameter("action")!=null){
   List<User> lstUser=new ArrayList<User>();
   String action=(String)request.getParameter("action");
   Gson gson = new Gson();
   response.setContentType("application/json");
   
   if(action.equals("list")){
    try{      
    //Fetch Data from User Table
    lstUser=dao.getAllUsers();   
    //Convert Java Object to Json    
    JsonElement element = gson.toJsonTree(lstUser, new TypeToken<List<User>>() {}.getType());
    JsonArray jsonArray = element.getAsJsonArray();
    String listData=jsonArray.toString();    
    //Return Json in the format required by jTable plugin
    listData="{\"Result\":\"OK\",\"Records\":"+listData+"}";   
    response.getWriter().print(listData);
    }catch(Exception ex){
     String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getMessage()+"}";
     response.getWriter().print(error);
     ex.printStackTrace();
    }    
   }
   else if(action.equals("create") || action.equals("update")){
    User user=new User();
    if(request.getParameter("userid")!=null){       
       int userid=Integer.parseInt(request.getParameter("userid"));
       user.setUserid(userid);
    }
    if(request.getParameter("firstName")!=null){
     String firstname=(String)request.getParameter("firstName");
     user.setFirstName(firstname);
    }
    if(request.getParameter("lastName")!=null){
       String lastname=(String)request.getParameter("lastName");
       user.setLastName(lastname);
    }
    if(request.getParameter("email")!=null){
       String email=(String)request.getParameter("email");
       user.setEmail(email);
    }
    try{           
     if(action.equals("create")){//Create new record
      dao.addUser(user);     
      lstUser.add(user);
      //Convert Java Object to Json    
      String json=gson.toJson(user);     
      //Return Json in the format required by jTable plugin
      String listData="{\"Result\":\"OK\",\"Record\":"+json+"}";           
      response.getWriter().print(listData);
     }else if(action.equals("update")){//Update existing record
      dao.updateUser(user);
      String listData="{\"Result\":\"OK\"}";         
      response.getWriter().print(listData);
     }
    }catch(Exception ex){
      String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace().toString()+"}";
      response.getWriter().print(error);
    }
   }else if(action.equals("delete")){//Delete record
    try{
     if(request.getParameter("userid")!=null){
      String userid=(String)request.getParameter("userid");
      dao.deleteUser(Integer.parseInt(userid));
      String listData="{\"Result\":\"OK\"}";        
      response.getWriter().print(listData);
     }
    }catch(Exception ex){
    String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getStackTrace().toString()+"}";
    response.getWriter().print(error);
   }    
  }
  }
  }
}

Make sure web.xml contains proper servlet mapping as shown below,

<?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>

7. Finally create JSP file, with definitions for jTable action urls and fields,

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>AJAX based CRUD operations using jTable in Servlet 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 () {
        $('#PersonTableContainer').jtable({
            title: 'Table of people',
            actions: {
                listAction: 'CRUDController?action=list',
                createAction:'CRUDController?action=create',
                updateAction: 'CRUDController?action=update',
                deleteAction: 'CRUDController?action=delete'
            },
            fields: {
                userid: {
                 title:'S.NO',
                    key: true,
                    list: true,
                    create:true
                },
                firstName: {
                    title: 'First Name',
                    width: '30%',
                    edit:false
                },
                lastName: {
                    title: 'Last Name',
                    width: '30%',
                    edit:true
                },
                email: {
                    title: 'Email',
                    width: '20%',
                    edit: true
                }                
            }
        });
        $('#PersonTableContainer').jtable('load');
    });
</script>
</head>
<body>
<div style="width:60%;margin-right:20%;margin-left:20%;text-align:center;">
<h1>AJAX based CRUD operations in Java Web Application using jquery jTable plugin</h1>
<h4>Demo by Priya Darshini, Tutorial at <a href="http://www.programming-free.com/2013/07/setup-load-data-jtable-jsp-servlet.html">www.programming-free.com</a></h4>
<div id="PersonTableContainer"></div>
</div>
</body>
</html>

Note that we have initialized jTable first with action urls to perform crud operations and then called 'load' method to load the table with server side data. jTable fires AJAX calls for each type of operation user performs on the table and sends required parameters along with request to server side. The field name should exactly match the name of columns as how we have defined it in the model class.

That is all! We are now good to run the project. If you have downloaded the source code I have provided, make sure you have created a mysql table with the same structure as mentioned in this article before trying to execute the project.

When the page initially loads, jTable plugin calls the url provided in listAction option to fetch results from server side and creates an html table with header, content and required icons as shown in the below screenshot,


When the user clicks on the '+ Add new record' link present at the top right corner of the table, a create record form is automatically generated by jTable such as this,



Note that in this example, only lastname and email columns are made editable with 'edit' option set to true. Hence when the user clicks on edit icon, the edit form is automatically generated such as this,


When the user clicks delete icon for a record, a confirmation dialog is shown to the user by jTable (confirmation is optional but open as default) :





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 900320017079248170

Post a Comment

  1. Its veru good Article
    But can you explain how did you do the configuration of column(hide and show)

    ReplyDelete
    Replies
    1. Hi,

      You can do this by setting list:true or false option in the fields section,

      fields: {
      userid: {
      title:'S.NO',
      key: true,
      list: true,
      }
      }

      Check this out, http://www.jtable.org/ApiReference#fopt-list

      Delete
    2. Hi, what a superb tutorial,.but i want import all ths to ecxel

      Delete
    3. pagination is not clearly defined. even if you set paging and pageSize, still all records are displayed more than the page size. I found a workaround this problem as follows :
      in the crudController, doPost(...) action
      Add the following lines :
      String start=(String)request.getParameter("jtStartIndex");
      String end=(String)request.getParameter("jtPageSize");
      these two lines are practically getting the start of page and page size

      Then adjust thedao.getAllUsers(...) to accept the start , and end params
      i.e. thedao.getAllUsers(start,end)

      inside the ..getAllUsers(start,end)
      {
      .
      ResultSet rs = statement.executeQuery("select * from tblUser LIMIT "+from+" , "+to);

      }

      Delete
  2. Hi, what a superb tutorial,... Now I want to have pagination in it, I know that it is possible, but how do I implement it?, I would need it asap,... ;-)

    ReplyDelete
    Replies
    1. Hi,

      I will try to write an article on how to implement paging and sorting in jtable in the coming week. For now, to understand in simple terms you just have to get the total record count of your table in server side and return json as shown below,

      { Result = "OK", Records = students, TotalRecordCount = tableRowCount}

      In the view(jsp),

      $('#StudentTableContainer').jtable({
      title: 'The Student List',
      paging: true, //Enable paging
      pageSize: 10, //Set page size (default: 10)

      actions: {
      listAction: '/Demo/StudentList',
      deleteAction: '/Demo/DeleteStudent',
      updateAction: '/Demo/UpdateStudent',
      createAction: '/Demo/CreateStudent'
      },
      fields: {
      StudentId: {
      key: true,
      create: false,
      edit: false,
      list: false
      },
      Name: {
      title: 'Name',
      width: '23%'
      },
      EmailAddress: {
      title: 'Email address',
      list: false
      }
      }
      }
      });

      Hope this helps!

      Delete
    2. Article on Pagination,

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

      Delete
  3. :-) and while you are @ it,... en inputfield tosearch, like it is possible for the datatables,... thank you very much in advance for your response!

    ReplyDelete
    Replies
    1. It is possible to search fields in jTable also but unlike datatables, this feature is kept external and can be done only on button click event. Refer to this link below,

      http://jtable.org/Demo/Filtering

      Hope this helps!

      Delete
  4. hi Priya!!
    Excellent article.waiting for Pagination one.....

    ReplyDelete
    Replies
    1. It is here,

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

      Delete
  5. hello priya,
    i was executing the same program with struts2 but not getting data in index.jsp.plz help me

    ReplyDelete
    Replies
    1. The example above will run only is sime MVC model and not in struts2 architecture. You may have to tweak this code to make it work.

      Delete
  6. Hi priya ..
    I am woking on it to improve ..can you suggest me how to place the (delete/save button first and then cancel) button as it is general way to display in the screen..not like (cancel save).how to display as (save cancel)??
    can you suggest me anything.

    ReplyDelete
    Replies
    1. Hi Chandan,

      Play around with jquery.jtable.js file. The components of popup dialog are dynamically populated using jquery and you can locate it there.

      Thanks,
      Priya

      Delete
  7. Hello Priya,
    Every thing is all right,nice article,I loved it.One thing I am facing problem at retrieve and setting combo box value in java how to solve it . Could you please suggest ?

    ReplyDelete
  8. I implemented (insert/update/delete/retrieve colour change etc) but I could not implement combobox value update and how to do view operation if I am showing small amount of data.Please suggest.....Awaiting your positive note

    ReplyDelete
  9. Hi, nice tutorial, do you know if it's possible to have multiple primary keys?

    ReplyDelete
  10. Dear Priya,
    Hope all is well at your end.Q:--How to show error message in jTable?

    ReplyDelete
    Replies
    1. Hi,

      Please raise your questions here on jTable jQuery plugin to get immediate help.

      https://github.com/hikalkan/jtable/issues?state=open

      Hope this helps!

      Thanks,
      Priya

      Delete
  11. Hi Priya,
    Its indeed a great tutorial. One problem that I'm facing is the jtable with data is launching in a new browser tab / window instead of in the div within the current window that I've specified. Any reason why this could be happening.

    Any suggestion will be appreciated.

    ReplyDelete
    Replies
    1. Thank you. This issue sounds very weird. Post your code with the details of your analysis on the issue in any of technical forums to get immediate help.

      Delete
  12. Hi Priya,
    Do you have any working example of Parent -child based implementaion?
    -thanks

    ReplyDelete
  13. Hello Priya
    You mentionned at some point that you would try to add a tutorial on pagination which would be absolutely great. Can we expect it some time ?
    thanks

    ReplyDelete
    Replies
    1. Hi Anna,

      Just published my tutorial on Pagination in jTable here,

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

      Thanks,
      Priya

      Delete
    2. Hello
      Very clear, thanks a lot, good job!

      Delete
  14. Hi Priya

    I am able to add more than one record in the jtable by using a for loop and jquery but the problem in CHROME browser is it adds all the records at a time not in a sequential order of for loop.It works fine in IE in a sequential order.can you please help me what I need to look into..
    Below is my code snippet
    for(var i=0; i<final_details.length;i++) {
    //alert("line item no before add="+final_details[i].line['#text']);
    $('#TranItemTableContainer').jtable('addRecord', {
    record: {
    line_no:final_details[i].line['#text'],
    item_type:final_details[i].itemType['#text'],
    item_no:final_details[i].itemno['#text'],
    qty:final_details[i].Quantity['#text'],
    ext_amt:final_details[i].Extamt['#text']
    }
    });

    }

    ReplyDelete
  15. hi priya
    this very nice post.can you provide this application in structs2 ?

    ReplyDelete
  16. can any one help , i am getting Can not load options for field detps while passing
    options: 'CRUDController?action=getDepts' in depts filed , how i can handle it in java where it is in C# return new { Result = "OK", Options = depts};

    ReplyDelete
  17. Hi Priya:

    I want know how i can upload photo user using that!. Please, help me!

    ReplyDelete
    Replies
    1. we can include image path that ll be displayed in jtable which can be in this way..
      image: {
      title: 'image',
      width: '10%',
      sorting: false,
      edit: false,
      create: false,
      display: function (responseJson) {
      var $img=null;
      $img = $('&ltimg src="Path of image" height="20px" title="Tooltip" /&gt');
      });
      return $img;
      }

      Delete
    2. Hello Chandan Kar, can u please tell me , how to upload image using jtable? you can email me at poudelas.123@gmail.com . It's an urgent....

      Delete
  18. How i can make my jtable scrollable with fixed header table?

    ReplyDelete
  19. Hello Priya,
    Could you suggest how to change color of child table data .i.e. Color of parent table is blue and wants to change of color of child table header and title.How could i do this? plz suggest....

    ReplyDelete
    Replies
    1. Hi Ranjan

      u can do it in jquery something like this





      div.jtable-main-container > table.jtable > thead {
      background-color: #c30000;
      position:absolute;
      }

      Delete
  20. hi.... i am facing a problem while running this code just (AJAX based CRUD operations in Java Web Application using jquery jTable plugin
    Demo by Priya Darshini, Tutorial at www.programming-free.com) this info is displayed ...nothing more information is displayd

    ReplyDelete
    Replies
    1. Did you create mysql table first and change database connection properties before running the sample code provided?

      Thanks,
      Priya

      Delete
    2. Hi your article is well but i need to add search functionality to this ,can u tell me how to add the feature to this article

      Delete
  21. I tried the example given(http://www.programming-free.com/2013/08/ajax-based-crud-operations-in-java-web.html) implementing with struts2.

    The json data is sent to the jsp page and when I load the data, I could print on the browser, but the table does not populate. When I alert the postdata in the method
    "load: function (postData, completeCallback) {}" I get it undefined, but when I try to paste the value of the json it prints well in the browser.

    May I know what could be the reason why it is not picking it up? Can someone throw some light on this. Thanks in advance.

    My Struts.xml



    /callerId.jsp
    /callerId.jsp
    /login.jsp


    My Action Class
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("application/json");
    UserDetails user = (UserDetails) session.get("user");
    //Fetch Data from User Table
    callerIds=sqlOImpl.getAllCallerIds(user);
    //Convert Java Object to Json
    JsonElement element = gson.toJsonTree(callerIds, new TypeToken>() {}.getType());
    JsonArray jsonArray = element.getAsJsonArray();
    listData=jsonArray.toString();
    //Return Json in the format required by jTable plugin
    listData="{\"Result\":\"OK\",\"Records\":"+listData+"}";
    response.getWriter().print(listData);

    My jsp
    $(document).ready(function () {
    $('#PersonTableContainer').jtable({
    title: 'List of Caller Ids',
    actions: {
    listAction: 'viewAllCallerIds',
    createAction:'addCaller',
    updateAction: 'updateCaller',
    deleteAction: 'deleteCaller'
    },
    fields: {
    id: {
    title:'S.NO',
    key: true,
    list: true,
    create:true
    },
    callerId: {
    title: 'Caller Id',
    width: '30%',
    edit:true
    }
    }
    });
    $('#PersonTableContainer').jtable('load');
    });




    ReplyDelete
  22. hi can you give me a code that cand export and import data from mysql database in jsp using jtable
    thanx

    ReplyDelete
  23. this tutorial is very very very good........ (Y)

    ReplyDelete
  24. Hi Priya Darshini, This tutorial is really awesome. very useful.
    One thing can you include in it "Search /Filter" Operation.
    It will be helpful in searching a record in large no. of records.

    ReplyDelete
  25. Hi, nice tutorial, do you know ho will do search filtering using servlets

    ReplyDelete
  26. i implemented this code by making changes to dao class.i am successfully able to list the table..but while updating i am getting an error i.e "An error occured while communicating to the server".

    i had below changes:

    public static void updateList(User user){
    JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
    String sql="update user set lastname=?,email=? where userid=?";

    jdbcTemplate.update(sql);

    }
    public static List getAllUsers(){
    JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);

    String sql="select * from user";
    List listUsers=jdbcTemplate.query(sql,new RowMapper(){

    @Override
    public User mapRow(ResultSet rs, int rowNum) throws SQLException {
    User user=new User();
    user.setUserid(rs.getInt("userid"));
    user.setFirstName(rs.getString("firstname"));
    user.setLastName(rs.getString("lastname"));
    user.setEmail(rs.getString("email"));
    return user;
    }

    });

    return listUsers;

    }
    can any one help me out plz

    ReplyDelete
  27. Replies
    1. I am also getting the same issue .... in reading the list of all users could you please able to share the answer to above error

      Delete
  28. how to write the field validations

    ReplyDelete
  29. How to set the date picker in fiels

    ReplyDelete
  30. How can I add the external fields name in the table....

    ReplyDelete
  31. Hi priya nice article...
    i just want to search bar in that table is that possible??

    ReplyDelete
  32. hi it was very nice article priya....
    i tried this but am not able to get table result only it is showing
    AJAX based CRUD operations in Java Web Application using jquery jTable plugin Demo by Priya Darshini, Tutorial at www.programming-free.com
    can you please help me on this...

    ReplyDelete
    Replies
    1. Download files are deleted.please upload project.it will really help....

      Delete
    2. Yes, this would be usefull!
      Nice tutorial!

      Thank you

      Delete
  33. Found download here : https://github.com/priyadb/AjaxCrudjTablePaginationSample

    ReplyDelete
  34. Hi priya
    That is Excellent work, can you explain how to show message dialog s

    ReplyDelete
    Replies
    1. It is part of the jQuery jTable library. Make sure you have jquery UI included in your page and it will show required message boxes.

      Delete
  35. Hi Priya,
    It was an awesome article and works like a charm. I have 2 queries.
    1) Can i move the edit action as the first column instead last column ?
    2) Is there any way to add filtering for each column [ the demo shows only for ASP.NET got confused with that ]

    ReplyDelete
    Replies
    1. 1. You have to play around with the css and js files of jQuery jTable library to do this. No functionality is defined to do this right now

      2. I think the latest versions have filtering added to it, but did not get enough time to look into it. May be I will write some in the near future.

      Delete
  36. Hi Priya,

    This tutorial is very helpful ...

    i am also new to JAVA .. so i am dealing with Jtable and i am trying to get Key field value on "delete" action. but it is not accessible.

    Can you please help me !!

    ReplyDelete
  37. Excellent tutorial,

    I have an issue, when the data is load in jtable and some records are loaded from database and I want to edit one of those the 'save' button is not working as expected, it doesn't do anything, I tried to debug using the javascript console but it hasn't worked, do you know what could it be? It only works after adding a new record in jtable.

    My code is the following:

    fields: {
    id: {
    key: true
    type: 'hidden'
    },
    partnerId: {
    type: 'hidden',
    defaultValue: partner
    },
    orgId: {
    type: 'hidden',
    defaultValue: $organization
    },
    sort: {
    title: 'Tipo de Gasto',
    options: {
    'FLETES' : 'Fletes',
    'Consumo' : 'Consumo',
    'Gasolina' : 'Gasolina',
    'Refacciones' : 'Refacciones'
    }
    },
    filename: {
    title: 'Archivo XML',
    create: false,
    edit: false
    },
    FileUpload: {
    title: 'File',
    list: false,
    create: true,
    edit: false

    }
    }

    ReplyDelete
  38. Hi priya, Thank u for your great tutorials. will u publish the tutorials of uploading the files in the database with jsp/servlets in near future? i m waiting for this.........

    ReplyDelete
  39. Hi Priya, This is really helpful. Is it possible to include Search option in the tutorial?

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

    ReplyDelete
  41. Latest java tutorials available at http://www.androidcoding.in/tutorials-java/

    ReplyDelete
  42. What an extremely wonderful post this is. Genuinely, perhaps the best post I've at any point seen to find in as long as I can remember. Goodness, simply keep it up.
    data science bootcamp malaysia

    ReplyDelete
  43. Incredibly conventional blog and articles. I am realy very happy to visit your blog. Directly I am found which I truly need. Thankful to you and keeping it together for your new post.
    iot training in delhi








    ReplyDelete
  44. These musings just knocked my socks off. I am happy you have posted this.
    training provider in malaysia

    ReplyDelete
  45. Here at this site actually the particular material assortment with the goal that everyone can appreciate a great deal.
    360DigiTMG big data course malaysia

    ReplyDelete
  46. Truly, this article is really one of the very best in the history of articles. I am a antique ’Article’ collector and I sometimes read some new articles if I find them interesting. And I found this one pretty fascinating and it should go into my collection. Very good work!

    Best Data Science Courses in Hyderabad

    ReplyDelete
  47. I have express a few of the articles on your website now, and I really like your style of blogging. I added it to my favorite’s blog site list and will be checking back soon…
    Best Data Science Courses in Hyderabad

    ReplyDelete
  48. Welcome to the Ajax cleaning services. We are providing all kinds of commercial and residential cleaning services from here. We have a good reputation on cleaning services. If you go through visited our Ajax cleaning services you will be clear about our services.

    ReplyDelete
  49. Replies
    1. Shapoorji Golf Land amenities and design are just a few of the things that can make a house feel like the perfect fit. At Shapoorji Golf Land, we understand the importance of finding a home that meets all of your needs, and we are proud to offer luxury living spaces that do just that.
      https://shapoorjipallonji.ind.in/shapoorji-pallonji-golf-land/

      Delete
  50. I appreciate your post thanks for sharing the information.
    white Bath Bomb boxes
    custom Cigarette boxes

    ReplyDelete
  51. Amazing product thanks for sharing with us It is very informative. If you need any type of boxes you can visit the link.
    Perfume Boxes new york
    personalized Necklace Boxes

    ReplyDelete
  52. I am glad to see this brilliant post. all the details are very helpful and good for us, keep up to good work.I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
    Java Classes in Pune

    ReplyDelete
  53. Great post! I am seeing the great contents and step by step read really nice information. I am gathered this concept and more information.
    Data Science Training in Hyderabad
    Data Science Course in Hyderabad

    ReplyDelete
  54. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work
    digital marketing courses in hyderabad with placement

    ReplyDelete
  55. Cool you write, the information is very good and interesting, I'll give you a link to my site.
    data science courses in aurangabad

    ReplyDelete
  56. It’s indeed a great and helpful piece of information. I am happy that you shared these terrific ideas with us. Please keep it up and thanks for sharing. Checkout How To Start A Vending Machine Business

    ReplyDelete
  57. introduction a new application soft ware its our soft ware information online which is about The Abnormal in Psychology

    ReplyDelete

  58. Your writing style is engaging and your ideas are well-researched Thanks for sharing your expertise with us

    ReplyDelete
  59. "Wow, this article really opened my eyes to a new perspective! I love how you explained such a complex topic in such a simple way. Looking forward to reading more from you. Keep up the great work!"
    msradix.
    website: https://www.msradix.com/egypt/

    ReplyDelete
  60. "Absolutely captivated by the depth of your insights in this article. 🌟 Your perspective offers a refreshing take on a topic that's often overlooked. Kudos for sparking engaging conversations and keeping us hooked from start to finish! Can't wait to explore more of your content."
    indiantradebird.
    website: https://www.indiantradebird.com/product/magnetic-destoner

    ReplyDelete
  61. Wow, what an insightful article! I've always been curious about this topic, and you've explained it so clearly. Your writing style makes it easy for someone like me, who's not an expert, to grasp the concepts. I particularly liked how you provided real-life examples to illustrate your points. It's evident that you've done thorough research, and I appreciate the effort you've put into this. Looking forward to reading more of your work! Keep up the great job! 🌟📚
    msradix.
    WEBSITE: https://www.msradix.com/south-africa/

    ReplyDelete
  62. "Wow, this article really struck a chord with me! The insights shared here are truly refreshing and thought-provoking. It's evident that the author has a deep understanding of the topic and has managed to present it in such an engaging way. I especially loved how the personal anecdotes woven into the content added a relatable touch. It's not every day that you come across such well-researched and eloquently written pieces. Kudos to the author for shedding light on this issue from a perspective that's both insightful and unique. Looking forward to reading more content like this in the future!"
    dholeratriangle.
    website: https://www.dholeratriangle.com/

    ReplyDelete
  63. "Great article! I really enjoyed reading this. You've made some excellent points, and your writing is so clear and engaging. I particularly liked [mention something specific from the post], as it really resonated with me. Keep up the good work, and I can't wait to read more from you!"
    indiantradebird.

    ReplyDelete
  64. Certainly! However, I'll need more specific information about the blog you'd like to comment on. Please provide the title or topic of the blog, and I can help you craft a relevant and engaging comment.
    indiantradebird

    ReplyDelete
  65. "Fantastic blog! Your writing style is engaging, and your insights are thought-provoking. I especially loved the way you explained the topic. Keep up the great work!"
    indiantradebird.
    website: https://www.indiantradebird.com/product/bag-printing-machine

    ReplyDelete
  66. "I absolutely loved reading your blog! Your unique perspective on the topic really grabbed my attention and left me wanting more. Can't wait to see what you'll write about next!"
    msradix.
    website: https://www.msradix.com/malaysia/

    ReplyDelete
  67. I would like to say thank you so much by my heart. Such a nice post is given by you. explained very well with the proper image. I got an idea from the post and improve my knowledge and keep tough with us
    https://spica.net.in/

    ReplyDelete
  68. Thanks for telling about this website

    ReplyDelete
  69. This is very well sharing out! I enjoyed reading your article . Thank you and keep these good articles coming. Can I share your content on my website put in your reference? https://jbovn.asia/

    ReplyDelete
  70. This piece is undoubtedly among the greatest in the annals of writing. As a collector of old "Article," I occasionally read current articles that pique my attention. Furthermore, this one caught my attention a lot and ought to be included to my collection. Excellent job!
    bespoke database development

    ReplyDelete

emo-but-icon

SUBSCRIBE


item