0% found this document useful (0 votes)
12 views

spring boot

Uploaded by

xaseb33520
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

spring boot

Uploaded by

xaseb33520
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Crud function how to perform the RESTful Web Service let

discuss with following annotations.


@PostMapping: annotation which used to create new record.
@GetMapping: annotation which used to reads a record.
@RequestMapping: annotation which used to search the record.
@PutMapping: annotation which used to update the existing record.
@DeleteMapping: annotation which used to delete the record.

Sp
rin
g
Bo
ot
Mv
c
Wo
rking Flow

First Create the Controller


StudentController
package com.example.SpringMongoProject.Controller;

import com.example.SpringMongoProject.Entity.Student;
import com.example.SpringMongoProject.Service.StudentServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("api/v1/student")
public class StudentController {

@Autowired
private StudentServices studentServices;

@PostMapping(value = "/save")
private String saveStudent(@RequestBody Student students) {

studentServices.saveorUpdate(students);
return students.get_id();
}
@GetMapping(value = "/getall")
public Iterable<Student> getStudents() {
return studentServices.listAll();
}

@PutMapping(value = "/edit/{id}")
private Student update(@RequestBody Student student, @PathVariable(name =
"id") String _id) {
student.set_id(_id);
studentServices.saveorUpdate(student);
return student;
}

@DeleteMapping("/delete/{id}")
private void deleteStudent(@PathVariable("id") String _id) {
studentServices.deleteStudent(_id);
}

@RequestMapping("/search/{id}")
private Student getStudents(@PathVariable(name = "id") String studentid) {
return studentServices.getStudentByID(studentid);
}

Create the Entity

Student
package com.example.SpringMongoProject.Entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection ="students")
public class Student {

@Id
private String _id;
private String studentname;
private String studentaddress;
private String mobile;

public Student(String _id, String studentname, String studentaddress, String


mobile) {
this._id = _id;
this.studentname = studentname;
this.studentaddress = studentaddress;
this.mobile = mobile;
}

public Student() {
}

public String get_id() {


return _id;
}

public void set_id(String _id) {


this._id = _id;
}

public String getStudentname() {


return studentname;
}

public void setStudentname(String studentname) {


this.studentname = studentname;
}

public String getStudentaddress() {


return studentaddress;
}

public void setStudentaddress(String studentaddress) {


this.studentaddress = studentaddress;
}

public String getMobile() {


return mobile;
}

public void setMobile(String mobile) {


this.mobile = mobile;
}

@Override
public String toString() {
return "Student{" +
"_id='" + _id + '\'' +
", studentname='" + studentname + '\'' +
", studentaddress='" + studentaddress + '\'' +
", mobile='" + mobile + '\'' +
'}';
}
}

Create repository

StudentRepo
package com.example.SpringMongoProject.Repo;

import com.example.SpringMongoProject.Entity.Student;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepo extends MongoRepository<Student,String> {
}

Create Service

StudentServices
package com.example.SpringMongoProject.Service;

import com.example.SpringMongoProject.Entity.Student;
import com.example.SpringMongoProject.Repo.StudentRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServices {

@Autowired
private StudentRepo repo;

public void saveorUpdate(Student students) {

repo.save(students);
}

public Iterable<Student> listAll() {

return this.repo.findAll();
}

public void deleteStudent(String id) {

repo.deleteById(id);
}

public Student getStudentByID(String studentid) {

return repo.findById(studentid).get();
}
}

React
Installing React
npx create-react-app front-end

After complete the installation and run the project using following command.
npm start

Now you see the React Welcome Page.


After that open the React project into VS code editor.
First Step go to the bootstrap respect website and copy the bootstrap style paste inside the head tag.
After that install the axios by typing the following command
npm i axios

Creating a new Component student.jsx Paste the following code


import axios from 'axios';
import {useEffect, useState } from "react";

function Student()
{

//Logic
const [studentid, setId] = useState('');
const [studentname, setName] = useState("");
const [studentaddress, setAddress] = useState("");
const [mobile, setMobile] = useState("");
const [students, setUsers] = useState([]);

useEffect(() => {
(async () => await Load())();
}, []);

async function Load()


{
const result = await axios.get(
"http://localhost:8081/api/v1/student/getall");
setUsers(result.data);
console.log(result.data);
}

async function save(event)


{
event.preventDefault();
try
{
await axios.post("http://localhost:8081/api/v1/student/save",
{
studentname: studentname,
studentaddress: studentaddress,
mobile: mobile
});
alert("Student Registation Successfully");
setId("");
setName("");
setAddress("");
setMobile("");
Load();
}
catch(err)
{
alert("User Registation Failed");
}
}

async function editStudent(students)


{
setName(students.studentname);
setAddress(students.studentaddress);
setMobile(students.mobile);
setId(students._id);
}

async function DeleteStudent(studentid)


{
await axios.delete("http://localhost:8081/api/v1/student/delete/" +
studentid);
alert("Student deleted Successfully");
Load();
}

async function update(event)


{
event.preventDefault();
try
{
await axios.put("http://localhost:8081/api/v1/student/edit/" + studentid
,
{

studentname: studentname,
studentaddress: studentaddress,
mobile: mobile

});
alert("Registation Updateddddd");
setId("");
setName("");
setAddress("");
setMobile("");
Load();
}
catch(err)
{
alert("Student Updateddd Failed");
}
}

//Design
return (
<div>
<h1>Student Details</h1>
<div class="container mt-4" >
<form>

<div class="form-group">
<label>Student Name</label>
<input type="text" class="form-control" id="studentname"
value={studentname}
onChange={(event) =>
{
setName(event.target.value);
}}
/>
</div>

<div class="form-group">
<label>Student Address</label>
<input type="text" class="form-control" id="studentaddress"
value={studentaddress}
onChange={(event) =>
{
setAddress(event.target.value);
}}
/>
</div>

<div class="form-group">
<label>Mobile</label>
<input type="text" class="form-control" id="mobile"
value={mobile}
onChange={(event) =>
{
setMobile(event.target.value);
}}
/>

</div>
<div>
<button class="btn btn-primary mt-4"
onClick={save}>Register</button>

<button class="btn btn-warning mt-4"


onClick={update}>Update</button>
</div>
</form>
</div>
<br/>
<table class="table table-dark" align="center">
<thead>
<tr>
<th scope="col">Student Name</th>
<th scope="col">Student Address</th>
<th scope="col">Student Mobile</th>

<th scope="col">Option</th>
</tr>
</thead>
{students.map(function fn(student)
{
return(
<tbody>
<tr>
<td>{student.studentname}</td>
<td>{student.studentaddress}</td>
<td>{student.mobile}</td>
<td>
<button type="button" class="btn btn-warning" onClick={()
=> editStudent(student)} >Edit</button>
<button type="button" class="btn btn-danger" onClick={() =>
DeleteStudent(student._id)}>Delete</button>
</td>
</tr>
</tbody>
);
})}
</table>
</div>
);
}

export default Student;

spring.application.name=SpringMongoProject
server.port = 8089

spring.data.mongodb = localhost
spring.data.mongodb.port = 27017
spring.data.mongodb.database=LindaDb
spring.jackson.default-property-inclusion=NON_NULL

You might also like