Home Reactjs Registation Form using React JS and Spring boot

Registation Form using React JS and Spring boot

14 min read
0
0
4,606

This React and Spring boot tutorial will teach you how to do basic database functions that are CREATE RETIEVE, UPDATE and DELETE and SEARCH using mysql Database. The INSERT, SELECT, UPDATE and DELETE statements can be used in any database system, because this is support by all relational database systems.

We will learn how to INSERT, SELECT, UPDATE and DELETE and  SEARCH in database by writing code to manage the records table in the database named employeeinfo.  records  table consist of following columns fname,lname,city,phone,salary.

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.

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 demo1

com.example.demo1
-------------------->Demo1Application.java 
// This is the main class of the programme where the programming runs.

Spring Boot MVC Structure
|
-------------------->Studentservice.java
com.example.demo1.service
|
--------------------->StudentController
com.example.demo1.controller
|
----------------------> Stuentrepository.java
com.example.demo1.repository
|
-----------------------> Student.java
com.example.demo1.Entity

Spring Boot Mvc Working Flow

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

i have created the table name  which is records in the database. this annotation  @Table(name=”Records”) indicate the table name of the database.

  1. Entity annotation @Entity indicate as Entity of class.
  2. Column annotation @Column indicate each column of the table.

Student.java

package com.example.demo1.Entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Records")
public class Student 
{	
    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
	
    @Column(name="fname")
    private String fname;
    
    @Column(name="lname")
    private String lname;
    
    @Column(name="city")
    private String 	city;
    
    
    @Column(name="phone")
    private String phone;
    
    @Column(name="salary")
    private String salary;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getFname() {
		return fname;
	}

	public void setFname(String fname) {
		this.fname = fname;
	}

	public String getLname() {
		return lname;
	}

	public void setLname(String lname) {
		this.lname = lname;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getSalary() {
		return salary;
	}

	public void setSalary(String salary) {
		this.salary = salary;
	}
}

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

StudentController.java

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo1.Entity.Student;
import com.example.demo1.repository.Studentrepository;
import com.example.demo1.service.StudentServices;

@RestController
public class StudentContoller 
{
	 @Autowired
	 private StudentServices services;
	 
	 @GetMapping("/getall")
	 public Iterable<Student>getStudents() 
	 {
		 return services.listAll();     
	 }

	 @PostMapping(value = "/save")
	 private long saveBook(@RequestBody Student students)   
	 {  
		 services.saveOrUpdate(students);  
		 return  students.getId();  
	 }
	   
	
	 @RequestMapping("/student/{id}")  
	 private Student getBooks(@PathVariable(name = "id") int studentid)   
	 {  
	 return services.getStudentById(studentid);  
	 }  
	 
	    
	 @PutMapping("/edit/{id}")

	    private Student update(@RequestBody Student students)   
	    {  
		   services.saveOrUpdate(students);  
	       return students;  
	    }  

	 @DeleteMapping("/delete/{id}")  
	 private void deleteStudent(@PathVariable("id") int id)   
	 {  
		 services.delete(id);  
	 }  
	
	  
	 
}

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

Studentservice.java

package com.example.demo1.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo1.Entity.Student;
import com.example.demo1.repository.Studentrepository;

@Service
public class StudentServices {
	
	@Autowired
    private Studentrepository repo;
	
	public Iterable<Student> listAll() {
        return this.repo.findAll();
    }
	
	//saving a specific record by using the method save() of CrudRepository  
	public void saveOrUpdate(Student students)   
	{  
		repo.save(students);  
	} 
	
	public Student getStudentById(long id)   
	{  
		return repo.findById(id).get();  
	}
		 
		 
	public void update(Student students, int id)   
	{  
		repo.save(students);  
	}  	

	public void delete(long id)   
	{  
		repo.deleteById(id);  
	}  
		  
}

EmployeeRepository.java

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

package com.example.demo1.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.example.demo1.Entity.Student;

@Repository
public interface Studentrepository extends CrudRepository<Student,Long> {
	
}

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

spring.datasource.url=jdbc:mysql://localhost:3306/employeeinfo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
server.error.whitelabel.enabled=false
server.port=8010
spring.datasource.username=root
spring.datasource.password=

spring.jpa.open-in-view=false
spring.thymeleaf.cache=false

React Js is a Frontend Framework.

Install React App

npx create-react-app my-app

After Installation what you have to do is.

Add these dependencies

npm install axios
npm install react-router-dom@5.2.0

First Create the component registation.js

registation.js

import axios from "axios";
import { useState } from "react";
import "../components/registation.css";

function Register()
{
   const [id, setId] = useState("");
   const [firstname, setFname] = useState("");
   const [lastname, setLname] = useState("");
   const [city, setCity] = useState("");
   const [phone, setPhone] = useState("");
   const [salary, setSalary] = useState("");

   async function handleSubmit(event)
    {
        event.preventDefault();
    try
        {
         await axios.post("http://localhost:8013/save", 
        {
        id: id,
        fname: firstname,
        lname : lastname,
        city : city,
        phone : phone,
        salary :salary 
        });
          alert("User Registation Successfully");
          setId("");
          setFname("");
          setLname("");
          setCity("");
          setPhone("");
          setSalary("");
        
        }
    catch(err)
        {
          alert("User Registation Failed");
        }
   }
    return (
        <div className="register-container">
     
            <form className="register-form" onSubmit={handleSubmit}> 
            <br></br>      
            <h1>Register</h1>
            <p>Fill in the Information Below</p>

            <input type="text" 
             name="id"
             placeholder="id"
                     
             onChange={(event) =>
              {
                  setId(event.target.value);       
              }}
            />

            <input type="text" 
            name="firstname" 
            placeholder="Firstname" 
            onChange={(event) =>
                {
                    setFname(event.target.value);       
                }}
            />

            <input type="text" 
            name="lastname"
            placeholder="lastname"
            onChange={(event) =>
                {
                    setLname(event.target.value);       
                }}           
            />

             
            <input type="text" 
            name="city" 
            placeholder="city"
            onChange={(event) =>
                {
                    setCity(event.target.value);       
                }}           
            />
        <input type="text" 
            name="phone" 
            placeholder="phone"
            onChange={(event) =>
                {
                    setPhone(event.target.value);       
                }}           
            />

    <input type="text" 
            name="salary" 
            placeholder="salary"
            onChange={(event) =>
                {
                    setSalary(event.target.value);       
                }}           
            />

            <button type="submit">Register</button>

    
            </form>     

     
        </div>
    )
}

export default Register;

Add the Style to the Registation form 

create file registation.css and do it.

registation.css

.register-container
{
   
   display: flex;
   height: 78vh;
   justify-content: center;
   align-items: center;

}

.register-form
{
  display: flex;
  flex-direction: column;
  min-width: 30vw;

}

h2{
    text-transform: uppercase;
    letter-spacing: 0.15rem;
    text-align: center;
    margin:0; 
}

input {

    padding-top: 0.9rem;
    padding-bottom: 0.9rem;
    padding-right: 0.9rem;
    margin: 0.5rem;
}

button
{
    background-color: black;
    color: white;
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
    text-transform: uppercase;
    letter-spacing: 0.15rem;
    border: 1px solid white;

}

.bottom-link
{
    text-decoration: none;
    color: black;
}

App.js

The is main file where we will call the compontents.

import Register from "./pages/registation";
import './App.css';
import {BrowserRouter,Switch,Route} from 'react-router-dom';

function App() {
  return (
    <div className="App">
       <BrowserRouter>
        <Switch>
          <Route path="/" exact>
          
               <Register/>
          </Route>
      </Switch>
    </BrowserRouter>
    </div>
  );
}

export default App;

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 Reactjs

Leave a Reply

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

Check Also

Enhancing Inventory Management with a POS System and PHP Queries

Introduction to Inventory Management with POS Systems Efficient inventory management is cr…