Home Jsp Building a JSP AJAX CRUD Application

Building a JSP AJAX CRUD Application

16 min read
0
0
30

Introduction to JSP AJAX CRUD Applications

Building web applications has become more dynamic with the integration of Java Server Pages (JSP) and Asynchronous JavaScript and XML (AJAX). This combination enables developers to create robust CRUD (Create, Read, Update, Delete) applications that enhance user experience through seamless interactions. In this blog post, we will explore the fundamentals of a JSP AJAX CRUD application, highlighting its benefits and how to implement it.

Benefits of JSP and AJAX Integration

The use of JSP for server-side processing, coupled with AJAX for client-side interactions, allows developers to construct applications that respond quickly without the need for full page reloads. This not only improves performance but also enhances usability, making CRUD operations appear more fluid and intuitive. Moreover, incorporating AJAX into a JSP application simplifies data handling and allows for real-time updates, significantly boosting overall user satisfaction.

Creating a JSP AJAX CRUD Application

To create a JSP AJAX CRUD application, start by setting up a basic JSP framework. Next, implement AJAX calls using JavaScript or jQuery to handle data requests to the server. Create JSP pages to serve as views for data entry and display. For the CRUD functionality, ensure that your application can handle SQL operations effectively to manipulate the data stored in your database. The integration of JSP and AJAX ideally culminates in a smooth workflow and enhances data management capabilities.

Do the System Step by Step

Index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <link href="bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css"/>
        <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
        <link href="datatable/datatables.min.css" rel="stylesheet" type="text/css"/>
        
    </head>
    <body>
        <nav class="navbar navbar-dark bg-dark">
            <h3 style="color:white;">Student Management Crud Ajax</h3>
        </nav>
        
        </br>
        
      
        <div class="container">
            <div class="row">
                <div class="col-sm-4">
                    <form id="frmStudent" name="frmStuent">
                        
                        <div class="form-group" align="left">
                            <label>Student Name</label>
                            <input type="text" id="stname" name="stname" placeholder="Student Name" class="form-control" required>
                        </div>
                        
                        <div class="form-group" align="left">
                            <label>Course</label>
                            <input type="text" id="course" name="course" placeholder="Course" class="form-control" required>
                        </div>
                        
                         <div class="form-group" align="left">
                            <label>Fee</label>
                            <input type="text" id="fee" name="fee" placeholder="Fee" class="form-control" required>
                        </div>
                        
                        <div class="form-group" align="left">
                            <button type="button" class="btn btn-success" id="save" onclick="addStudent()">Add</button>
                             <button type="button" class="btn btn-warning" id="rest" onclick="reSet()">Reset</button>
                            
                        </div>
                        
                        
                        
                        
                    </form>

                </div>
                
                <div class="col-sm-8">
                    <div class="panel-body">
                        <table id="tbl-student" class="table table-bordered" cellpadding="0" cellspacing="0" width="100%">
                            <thead>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                            </thead>
                        </table>
                        
                        
                        
                    </div>
                   
                    
                    
                    
                    
                    
                </div>
                
                
            </div>
            
        </div>
        
  
        <script src="jquery/jquery-3.4.1.js" type="text/javascript"></script>
        <script src="jquery/jquery.validate.min.js" type="text/javascript"></script>
        <script src="datatable/datatables.min.js" type="text/javascript"></script>
       
        <script>
             var isNew = true;
             var studid = null;
             getall();
   
             function addStudent()
             {
                 
                 if($("#frmStudent").valid())
                 {
                     var url = "";
                     var data = "";
                     var method;
                     
                     
                     if(isNew == true)
                     {
                         url = 'addstudent.jsp';
                         data = $("#frmStudent").serialize();
                         method = 'POST'
                         
                       
                     }
                     else
                     {
                         
                          url = 'editstudent.jsp';
                         data = $("#frmStudent").serialize() + "&studid=" + studid;
                         method = 'POST'
                     }

                     
                     $.ajax({
                         
                         type: method,
                         url : url,
                         dataType : "JSON",
                         data : data,
                         
                         success:function(data)
                         {
                             $('#stname').val("");
                             $('#course').val("");
                             $('#fee').val("");
                             
                             getall();
                             
                             if(isNew == true)
                             {
                                 alert("Record Addedd");
                             }
                             else
                             {
                                 
                                 alert("Record Updatedd");
                             }
 
                         }

                     });

             }
            
            
            
    }
    
    
    function getall()
    {
        $('#tbl-student').dataTable().fnDestroy();
        $.ajax({
            
            url:"all_student.jsp",
            type: "GET",
            dataType: "JSON",
           success:function(data)
           {
             
               $('#tbl-student').dataTable({
                   "aaData":data,
                   "scrollX":true,
                   "aoColumns":
                           [
                                {"sTitle" : "Student Name","mData" : "stname"},
                                {"sTitle" : "Course","mData" : "course"},
                                {"sTitle" : "Fee","mData" : "fee"},
                                 {"sTitle" :
                                   "Edit",
                                   "mData" : "id",
                                   "render" : function(mData,type,row,meta)
                                   {
                                       return '<button class="btn btn-success" onclick="get_details('+ mData  + ')">Edit</button>';
                                   }
                                },
                                {"sTitle" :
                                   "Delete",
                                   "mData" : "id",
                                   "render" : function(mData,type,row,meta)
                                   {
                                       return '<button class="btn btn-danger" onclick="get_Delete('+ mData  + ')">Delete</button>';
                                   }
                                },
                           ]
               });
           } 
        });
 
    }
    
    
    
    function get_details(id)
    {
        
        $.ajax({
            
            type : "POST",
            url : "edit_return.jsp",
            data : {"id" : id},
            
            success:function(data)
            {
               isNew = false
               var obj = JSON.parse(data);
               studid = obj[0].id
               $('#stname').val(obj[0].stname);
               $('#course').val(obj[0].course);
                $('#fee').val(obj[0].fee); 
                
            }

        }); 
    }
    
      
    function get_Delete(id)
    {
        
      $.ajax({
          
          type: "POST",
          url : 'delete_student.jsp',
          dataType : "JSON",
          data: {"id" : id},
          
          success:function(data)
          {
             alert("Record Deleted"); 
             getall();
              
          }

      });
 
    }
  
        </script>
   
    </body>
</html>

addstudent.jsp

<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="java.sql.*" %>
<%  

  JSONArray list = new JSONArray();
  
    String studentname = request.getParameter("stname");
    String course = request.getParameter("course");
    int fee =  Integer.parseInt(request.getParameter("fee"));
    
    
    Connection con;
    PreparedStatement pst;
    

    try
    {
        JSONObject obj = new JSONObject();
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud","root","");
        pst = con.prepareStatement("insert into records(stname,course,fee)values(?,?,?)");
        pst.setString(1, studentname);
        pst.setString(2, course);
        pst.setInt(3, fee);
        pst.executeUpdate();
        obj.put("name", "success");
        list.add(obj);
        out.println(list.toJSONString());
        out.flush();
        
    }
    catch(Exception ex)
    {
        
        
    }




%>

all_student.jsp

<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="java.sql.*" %>
<%
    
JSONArray list = new JSONArray();
    
  Connection con;
  PreparedStatement pst;
  ResultSet rs;
  
        try
        {
            
     
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud","root","");
        String query = "select * from records";
        Statement stmt = con.createStatement();
        rs = stmt.executeQuery(query);
        
        while(rs.next())
        {
            JSONObject obj = new JSONObject();
             int id = rs.getInt("id");
            String stname = rs.getString("stname");
            String course = rs.getString("course");
            int fee = rs.getInt("fee");
            
            obj.put("id", id);
            obj.put("stname", stname);
            obj.put("course", course);
            obj.put("fee", fee);
            list.add(obj);
            
        }
        
        out.print(list.toJSONString());
        out.flush();
            
            
        }
        catch(Exception ex)
        {
        }

%>

edit_return.jsp

<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="java.sql.*"%>

<%
    
JSONArray list = new JSONArray();
    
  Connection con;
  PreparedStatement pst;
  ResultSet rs;
  

    try
        {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud","root","");
        int id = Integer.parseInt(request.getParameter("id"));
        
        pst = con.prepareStatement("select id,stname,course,fee from records where id= ?");
        pst.setInt(1, id);
        rs = pst.executeQuery();
        
        if(rs.next() == true)
        {
            int id1 = rs.getInt("id");
            String stname = rs.getString("stname");
            String course = rs.getString("course");
            int fee = rs.getInt("fee");
            
            JSONObject obj = new JSONObject();
            
            obj.put("id", id1);
            obj.put("stname", stname);
            obj.put("course", course);
            obj.put("fee", fee);
            list.add(obj); 
        }
        
        out.print(list.toJSONString());
        out.flush();
        
        
     
     
        }
 catch(Exception ex)
         {
             
             
         }

%>

editstudent.jsp

<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="java.sql.*"%>
<%
    

 JSONArray list = new JSONArray();
 
    
String stname = request.getParameter("stname");
String course = request.getParameter("course");
int fee = Integer.parseInt(request.getParameter("fee"));
int studid = Integer.parseInt(request.getParameter("studid"));


 Connection con;
 PreparedStatement pst;
 

try
    {
        JSONObject obj = new JSONObject();
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud","root","");
        pst = con.prepareStatement("update records set stname=?,course=?,fee=? where id = ?");
        pst.setString(1, stname);
        pst.setString(2, course);
        pst.setInt(3, fee);
        pst.setInt(4, studid);
        pst.executeUpdate();
        obj.put("name", "success");
        list.add(obj);
        out.println(list.toJSONString());
        out.flush();

    }
catch(Exception ex)
    {
    }
%>

delete_student.jsp

<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="java.sql.*"%>

<%
    
JSONArray list = new JSONArray();
Connection con;
PreparedStatement pst;

int id = Integer.parseInt(request.getParameter("id"));

        try
        {
        JSONObject obj = new JSONObject();
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/studcrud","root","");
        pst = con.prepareStatement("delete from records where id = ?");
        pst.setInt(1, id);
        pst.executeUpdate();
        obj.put("name", "Success");
        list.add(obj);
        out.println(list.toJSONString());
        out.flush();

        }

        catch(Exception ex)
        {
        }
%>

I attached the Video Below.do the work while watching the Video

 

 

 

 

 

 

 

 

    Load More Related Articles
    Load More By admin
    Load More In Jsp

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Check Also

    JSP to JSP Communication: A Complete Guide to Dynamic Java Web Development

    Java Server Pages (JSP) is a powerful technology used to develop dynamic web applications …