Datatable

listing.html

<!-- https://datatables.net/examples/server_side/simple.html -->
<!-- https://datatables.net/manual/ajax -->
<!-- https://datatables.net/manual/ajax#Column-data-points -->
<!-- https://stackoverflow.com/questions/64526856/how-to-add-edit-delete-buttons-in-each-row-of-datatable -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
  
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap5.min.css">

    <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
    <title>Document</title>
</head>
<body>
<table id="example" class="display table table-striped" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Address</th>
                <th>Salary</th>
                <th>Action</th>
            </tr>
        </thead>
    </table>
</body>
<script>
    $(document).ready(function () {
    $('#example').DataTable({
        processing: true,
        serverSide: true,
        ajax: 'http://ciacloud.in/juhi/rems/get_employees.php',
        columns: [
            { data: 'name'},
            { data: 'address'},
            { data: 'salary'},
            { 
                data: 'id',
                render: (data,type,row) => {
                    console.log({data,type,row})
                   return `<a href='edit_form.php?id=${data}'>Edit</a> | <a href='delete.php?id=${data}'>Delete</a>`;
                 }
            }
        ],
        columnDefs: [
            { orderable: false, targets: -1 },
            {
                "defaultContent": "-",
                "targets": "_all"
            }],
            order: [0,1,2,3],
    });
});
</script>
</html>

get_employees.php

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$params = $_REQUEST;
header('Access-Control-Allow-Origin: *');

$search = isset($params['search']['value'])  && $params['search']['value'] != '' ? $params['search']['value'] : '';

try {
  $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $where = '';

  if($search !== '')
	  $where = " name LIKE '$search%' ";
  else
	  $where = " 1 = 1 ";

  $sort_columns = ['name', 'address', 'salary'];
  $sort_column_index = $params['order'][0]['column'];
  $sort_order = isset($params['order'][0]['dir']) && $params['order'][0]['dir'] != 1 ? $params['order'][0]['dir'] : 'desc';

  $order_by = " $sort_columns[$sort_column_index] $sort_order";
	
  $offset = $params['start'];
  $limit = $params['length'];

  $sql = "SELECT * FROM employees WHERE $where ORDER BY $order_by LIMIT $offset, $limit";
  $stmt = $conn->prepare($sql);
  $stmt->execute();

  // set the resulting array to associative
  $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
  $employees = $stmt->fetchAll();

} catch(PDOException $e) {
  echo "Error: " . $e->getMessage();
}

$count_sql = "SELECT COUNT(*) FROM employees WHERE $where";
$result = $conn->prepare($count_sql); 
$result->execute(); 
$totalRecords = $result->fetchColumn(); 

$conn = null;


$json_data = array(
		"draw"            => intval( $params['draw'] ),
		"recordsTotal"    => intval( $totalRecords ),
		"recordsFiltered" => intval($totalRecords),
		"data"            => $employees,
		"count_sql"	=> $count_sql,
		"sql"		=> $sql,
	);

echo json_encode($json_data);

Spring Boot

CalcController.java

package com.javatest.demo;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

class MyCalc {
    private int num1;
    private int num2;

    public int getNum1() {
        return num1;
    }
    public void setNum1(int num1) {
        this.num1 = num1;
    }
    public int getNum2() {
        return num2;
    }
    public void setNum2(int num2) {
        this.num2 = num2;
    }
    
    @Override
    public String toString() {
        return "MyCalc [num1=" + num1 + ", num2=" + num2 + "]";
    }
}

@RestController
public class CalcController {


    @RequestMapping("test")
    public String test() {
        return "Testing....";
    }

    /** Read query params */
    @RequestMapping("mycalc")
    @GetMapping
    public String getMet(@RequestParam("num1") int x, @RequestParam int y) {
        return String.format("%s + %s = %s", x, y, x+y);
    }

    /** Read raw json data */
    @PostMapping("mycalc")
    public String postMet(@RequestBody MyCalc obj) {
        int x = obj.getNum1();
        int y = obj.getNum2();

        return String.format("%s - %s = %s", x, y, x - y);
    }

    /** Read form data */
    @PutMapping("mycalc")
    public String putMet(
        @RequestParam("num1") int x,
        @RequestParam("num2") int y) {
        return String.format("%s * %s = %s", x, y, x * y);
    }

    /** Read from raw json */
    @DeleteMapping("mycalc")
    public String deleteMet(@RequestBody MyCalc obj) {
        int x = obj.getNum1();
        int y = obj.getNum2();
        return String.format("%s / %s = %s", x, y, x / y);
    }

}

src/main/resources/application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/<databasename>
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

User.java (POJO/DAO/JPA)

package com.javatest.demo;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name="users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String age;
    private String city;
    private int quota;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public int getQuota() {
        return quota;
    }
    public void setQuota(int quota) {
        this.quota = quota;
    }


    
    // getters and setters

    
}

UserController.java

package com.javatest.demo;


import java.util.List;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.jpa.repository.JpaRepository;

interface UserRepository extends JpaRepository<User, Long> {
    // Custom queries can be defined here
}

@RestController
@RequestMapping("users")
public class UserController {
    
    private final UserRepository userRepository;
    
    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @RequestMapping("")
    public String index() {
        return "I am from index";
    }

    @RequestMapping("listing")
    public List<User> listing() {
        // List<User> users = new ArrayList<>();
        return userRepository.findAll();
    }

    @DeleteMapping("delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        // Check if the user with the specified ID exists
        if (userRepository.existsById(id)) {
            userRepository.deleteById(id);
            return String.format("User %s is deleted successfully", id);
        } else {
            // Handle the case when the user does not exist (e.g., return an error response)
            // You can throw an exception or return an appropriate response based on your application's requirements.
        }
        return "";
    }

    @PostMapping("create")
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }


    @GetMapping("get-single/{id}")
    public User getUserById(@PathVariable Long id) {
        // Use the UserRepository to fetch the user by ID
        return userRepository.findById(id).orElse(null);
    }

    @PutMapping("/update/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
        // Check if the user with the specified ID exists
        userRepository.findById(id).orElse(null);

        // Set the ID of the updated user to the specified ID
        updatedUser.setId(id);

        // Save the updated user to the database
        return userRepository.save(updatedUser);
    }

}

DemoApplication.java (Run this file to serve spring boot application)

package com.javatest.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

File Structure

.
├── HELP.md
├── mvnw
├── mvnw.cmd
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── javatest
│   │   │           └── demo
│   │   │               ├── CalcController.java
│   │   │               ├── DemoApplication.java
│   │   │               ├── User.java
│   │   │               └── UserController.java
│   │   └── resources
│   │       ├── application.properties
│   │       ├── static
│   │       └── templates
│   └── test
│       └── java
│           └── com
│               └── javatest
│                   └── demo
│                       └── DemoApplicationTests.java
└── target
    ├── classes
    │   ├── application.properties
    │   └── com
    │       └── javatest
    │           └── demo
    │               ├── CalcController.class
    │               ├── DemoApplication.class
    │               ├── MyCalc.class
    │               ├── User.class
    │               ├── UserController.class
    │               └── UserRepository.class
    └── test-classes
        └── com
            └── javatest
                └── demo
                    └── DemoApplicationTests.class

23 directories, 18 files

POC

VSCode Extesnsions