Home Spring boot Spring Boot Ajax jQuery Crud Application

Spring Boot Ajax jQuery Crud Application

15 min read
0
0
5,506

This Spring boot Ajax jQuery Crud tutorial will teach you how to do basic database functions that are CREATE, RETIEVE, UPDATE ,DELETE data using MySQL Database. The main purpose of we have use Ajax is without refresh the page.this project we covered all the crud operations.

The package structure, you must following the standard package structure of spring boot and spring framework.for the example i have created the project name SpringCrud

com.example.student
-------------------->studentApplication.java 
// This is the main class of the programme where the programming runs.
 
Spring Boot MVC Structure
|
-------------------->Studentservice.java
com.example.student.service
|
--------------------->StudentController
com.example.student.controller
|
----------------------> Studentrepository.java
com.example.student.repository
|
-----------------------> Student.java
com.example.student.Entity

First you must Create the package com.example.student.Entity. inside the package you have to create the class.

  1. Entity annotation @Entity indicate as Entity of class.

Student.java

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;
    private String studentname;
    private String course;
    private int fee;
    public Student() {

    }
    public Student(Long id, String studentname, String course, int fee) {
    
        this.id = id;
        this.studentname = studentname;
        this.course = course;
        this.fee = fee;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getStudentname() {
        return studentname;
    }
    public void setStudentname(String studentname) {
        this.studentname = studentname;
    }
    public String getCourse() {
        return course;
    }
    public void setCourse(String course) {
        this.course = course;
    }
    public int getFee() {
        return fee;
    }
    public void setFee(int fee) {
        this.fee = fee;
    }

}

after that you have to Create the package com.example.student.controller . inside the package you have to create the class

StudentController.java

package com.example.emp.controller;

import java.util.List;

import com.example.emp.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import com.example.emp.domain.Student;
import com.example.emp.service.StudentService;

@RestController
@RequestMapping("Student")
public class StudentController {

     @Autowired
        private StudentService service;

    private StudentRepository studentRepository;

        @RequestMapping(value = "/save", method = RequestMethod.POST)
        public String saveStudent(@ModelAttribute("student") Student std) {
            service.save(std);
            return "{\"status\":\"success\"}";
        }

        @RequestMapping(value = "/list", method = RequestMethod.GET)
        public List<Student> listStudents() {
            List<Student> liststudent = service.listAll();
            return liststudent;
        }


    @RequestMapping(value = "/get/{id}")
    public Student getStudentPage(@PathVariable(name = "id") int id) {
        Student stdd = service.getid(id);
        return stdd;
    }


    @PostMapping(value = "/edit/{id}")
    public String updateStudent(@PathVariable("id") long id,  Student student)
    {
        student.setId(id);
        service.save(student);
        return "{\"status\":\"success\"}";

    }

        @RequestMapping("/delete/{id}")
        public String deletestudent(@PathVariable(name = "id") int id) {
            service.delete(id);
            return "{\"status\":\"success\"}";
        }

}

First you must Create the package com.example.student.service . inside the package you have to create the class

Studentservice.java

@Service
public class StudentService {
    
    @Autowired
    private StudentRepository repo;
    
    public List<Student> listAll() {
        return repo.findAll();
    }
     
    public void save(Student std) {
        repo.save(std);
    }



    public Student getid(long id) {
        return repo.findById(id).get();
    }



    public Student get(long id) {
        return repo.findById(id).get();
    }
     
    public void delete(long id) {
        repo.deleteById(id);
    }

}

StudentRepository.java

First you must Create the package com.example.Student.repository inside the package you have to create the Interface here.

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

}

 

After that you must set database path and project configuration in application.properties file.

spring.application.name=crudnew
server.port=8084
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ajaxschool?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root123
#jpa vendor adapter configuration
spring.jpa.database-platform=org.hibernate.dialect.MySQL57Dialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true

Create the Page of Front End as index.html

index.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/cosmo/bootstrap.min.css" />
    <script src="component/jquery-3.4.1.min.js" type="text/javascript"></script>
    <script src= "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" ></script>
    <link href="component/DataTables/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="studentname" name="studentname" 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="update" onclick="updateStudent()">Update</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>
                    <tr><th>Student Name</th><th>Course</th><th>Fee</th><th>Edit</th><th>Delete</th></tr>
                    </thead>
                </table>

            </div>

        </div>


    </div>

</div>


<script src="component/jquery.validate.min.js" type="text/javascript"></script>

<script src="component/DataTables/datatables.min.js" type="text/javascript"></script>



<script>
    var isNew = true;
    var studid = null;
    getall();

    //Add Records
    function addStudent()
    {

        if($("#frmStudent").valid())
        {
            var url = "";
            var data = "";
            var method;


            if(isNew == true)
            {
                url = '[[${@environment.getProperty('api.base.path')}]]/Student/save';
                data = $("#frmStudent").serialize();
                method = 'POST'
            }


            $.ajax({
                type: method,
                url : url,
                dataType : "JSON",
                data : data,
                success:function(data)
                {
                    $('#studentname').val("");
                    $('#course').val("");
                    $('#fee').val("");
                    console.log(data);
                    getall();

                    if(data.status == "success")
                    {
                        alert("Record Addedd");
                    }
                    else
                    {

                        alert("Record Updateedddd");
                    }
                }

            });
        }
    }

    //Update Records

    function updateStudent()
    {
    if($("#frmStudent").valid())
    {
        var url = "";
        var data = "";
        var method;


        if(isNew == false)
        {

            url = '[[${@environment.getProperty('api.base.path')}]]/Student/edit/' + studid ;
            data = $("#frmStudent").serialize();
            method = 'POST'

        }
        $.ajax({
            type: method,
            url : url,
            dataType : "JSON",
            data : data,
            success:function(data)
            {
                $('#studentname').val("");
                $('#course').val("");
                $('#fee').val("");
                console.log(data);
                getall();

                if(data.status == "success")
                {
                    alert("Record Updateedddd");
                }
                else
                {

                    alert("Record Error");
                }
            }

        });
    }
    }


    //View Records

    function getall()
    {
        $('#tbl-student').dataTable().fnDestroy();
        $.ajax({

            url:"[[${@environment.getProperty('api.base.path')}]]/Student/list",
            type: "GET",
            dataType: "JSON",
            success:function(data)
            {
                $("#tbl-student").dataTable({
                    "data": data,
                    "columns": [
                        { data: 'studentname' },
                        { data: 'course' },
                        { data: 'fee' },
                        {
                            data: null,
                            render : function(data, type, full, meta)
                            {
                                return '<button class="btn btn-success" onclick="get_details('+ data.id  + ')">Edit</button>';
                            }
                        },
                        {
                            data: null,
                            render : function(data, type, full, meta)
                            {
                                return '<button class="btn btn-danger" onclick="get_Delete('+ data.id  + ')">Delete</button>';
                            }
                        }

                    ]
                });
            }
        });

    }

    //Get Records

    function get_details(id)
    {

    $.ajax({

        type : "POST",
        url : "[[${@environment.getProperty('api.base.path')}]]/Student/get/" + id,


        success:function(data)
        {
           console.log(data)

            isNew = false
            console.log(data);

            studid = data.id
            $('#studentname').val(data.studentname);
            $('#course').val(data.course);
            $('#fee').val(data.fee);

        }

    });
    }


    //Delete Records
    function get_Delete(id)
    {

        $.ajax({

            type: "POST",
            url : "[[${@environment.getProperty('api.base.path')}]]/Student/delete/" + id,
            dataType : "JSON",

            success:function(data)
            {
                alert("Record Deleted");
                $('#studentname').val("");
                $('#course').val("");
                $('#fee').val("");
                getall();

            }

        });

    }

</script>

</body>
</html>

Buy the Source Code Here

i have attached the video link below. which will do this tutorials step by step.

 

Load More Related Articles
Load More By admin
Load More In Spring boot

Leave a Reply

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

Check Also

Laravel 11 CRUD Mastering RESTful API MVC with Repository Pattern

In this tutorial will teach Laravel 11 Api MVC with Repository Pattern Crud Application st…