Final Code is Provided
On the bottom side
For Video Series :
Kindly Reach at me
Telegram Channel Link
: https://t.me/scientificeyeeducation
Whatsapp Group Link :
https://chat.whatsapp.com/KBNgnijK4vI5yZ64hAKKOk
Facebook Group : https://www.facebook.com/groups/415952859495530/
Requirement
1. Java (JDk 1.8)
2. Maven
3. Any IDE
Step 1 : [ Generate Zip File and Start Project]
Go To start.spring.io
In This
Website you need to filled proper
details of configuration.
Add Following
Dependency
1.
Rest Repositories
2.
H2 Database
3.
Lombok
4.
Spring Data JPA
and then
Generate Zip File . Unzip the Generated File and Open in Any favourite Text
Editor
I am used Eclipse for this Project.
Step 2 : Creating React App
In order to
create react app there must be Node JS installed in your system . if node
js is not installed in your pc then kindly go to the Node Js Website and
download it.
After installing Node js now you go to the
Spring project .from that spring project directory go to terminal and then write the following
command . npx create-react-app client. It take some time to install dependency
.
Here CRM is my Spring boot Project . Inside Crm
I typed npx create-react-app client. Now its download required dependency .
|
After
Completing this . type client and hit enter. This will go to client directory.
And then typed npm start. This will lead to run your react project
Step 3 :
Make a
model package inside crm package. And then make a Contact
Class in model package.
For contact
Class . We need to add Four attribute as
Follow.
1.
firstName String
2.
lastName String
3.
email String
4.
Id int
here id
have @Id and @GeneratedValue(streategy=GenerationType.IDENTITY) annotation.
We have to
add @Data and @Entity annotation on the top of Class name declaration.
@Data annotation Comes from Lombok.data
that reduce to write getter and setter method for attribute.
Then we
need to make two constructor . One is default constructor and second is
parameterized constructor having all parameters except id.
Step 4] Then we make a repository interface
inside same package .
Here is how
Repository Interface looks like
We take CrudRepository . There are two
Repository options. One is JPARepository
and Second is CrudRepository. When
we extends CrudRepository it takes two
parameter. One is the Model class
name and second is the Type of
primary key. Here is model class is Contact and primary key is id having type int.
Step 5] Preload Values
For Preloading some of values . We need to first create a class a InitialValueLoader.. inside same model package. After creating class we need to implement CommandLineRunner Interface on same class. That overrides method
public
void run(String… args) throws Exception{}.
Add @Component annotation on the top of class name
declaration.
In that
same class we need to inject dependency of ContactRepository
using following manner.
I’ve attached Screenshot here to understand how you insert values inside entity.
Step 4 ] Define a base path of Rest Endpoint.
When you
generally run project it host on the particular port in following manner. Let
say if you define port a: 8081 to run. Then your rest endpoint url looks like :
localhost:8081. If you add something after 8081 like your application name or
anything. You need to define base-path . let take an example your application
name is demo and you need to add after port number. Then you need to go application.properties file and add spring.data.rest.base-path=/demo. Now whenever you run the project
your base url becomes : localhost:8081/demo
Step 5]Test Rest Point.
Open
Postman tool and in the url section type the following :
http://localhost:8080/api and use get Request for this.
You will get response
following .
If you get
same response then your application is running perfectly.
Now we test
each condition .
In the URL section type
http://localhost:8080/api/contacts and use get request .
This will give you list of contact present inside database .let look the following picture.
Hurray..
There are some peoples who not get reponse. Like this. Ok wait.. you have to
fix some issue. Go to the model
class and open Contact pojo and make
the field public. Yes that not saafe
but for testing purpose we need to change. After modifying pojo ..hit again the
above URL. And this time surely you will get response.
Now
let move to the post operation. Now you want to add one more contact. Its very
easy. go to url section hit post method for the following url : http://localhost:8080/api/contacts
Wait you need a json to add contact.
What we do
over here. : We go to body section select raw and at the last we choose JSON
type. We made Requestmethod to POST.
Now you
just required one json to pass from. Let say {“firstName”:”Capton”,”lastName”:”jack
sparrow”,”email”: “captionjacksparrow@gmail.com”}
This is how
post endpoint works.
Now We
going to test ContactById api. So
for that you first need to hit get api for contacts.
You will
get response like this.
{
"_embedded": {
"contacts": [
{
"firstName": "Praful",
"lastName": "Sonawane",
"email": "prafulsonawane400@gmail.com",
"_links": {
"self": {
"href": "http://localhost:8080/api/contacts/1"
},
"contact": {
"href": "http://localhost:8080/api/contacts/1"
}
}
},
{
"firstName": "Captain",
"lastName": "Jack Sparrow",
"email": "captainjacksparrow@gmail.com",
"_links": {
"self": {
"href": "http://localhost:8080/api/contacts/2"
},
"contact": {
"href": "http://localhost:8080/api/contacts/2"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/contacts"
},
"profile": {
"href": "http://localhost:8080/api/profile/contacts"
}
}
}
Inside Links section there is one more link for self so pick up the url of self and hit get request for that. You will get Contact By Id.
Now move on Put Restpoint. For put you require same
url as required to find by id. And hit put operation but wait you need to sent
pojo of contact to manipulate data on server.
The following SS Show you how to hit Put Url on Server
Now Lastly We going to test Delete Restpoint.
For Delete you need same url but just required to
change Requestmethod to delete and hit send
This will delete the Object from database.
Step 5] Now in
step 5 We move to React Js For Some basic design
First go to App.js
and remove everything inside <div
className=”App”></div>
Inside the
pointer you just write <Contact />
. So What basically Contact is …Contact is React Component that we will going
to define .but wait When you Write the above
tag you need to define the export path of that component in the header section.
So let define Contact Element define from
‘./component/Contact’ package. Now you have to make component folder
inside src directory. After making
component folder now you make javascript file and give Contact name to it.
In
Contact.js file you need to import React, {Component}on top of file
So now let
look how your Contact file looks like
Import
React, {Component} from ‘react’;
export
default Contact extends Component{
constructor(props){
super(props);
this.state={
contacts
: [],
}
}
render(){
return{
<div>
<h1>Hello</h1>
</div>
}
}
}
After
writing above code in your Contact js
file . Now save and check you get similar output like below
Step 6] Add
Material Themes and Css to React Project
Go to the
following Link : https://materializecss.com/getting-started.html
Go to CDN
Section . Copy the following block of code
<!--
Compiled and minified CSS -->
<link
rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and
minified JavaScript -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
And
paste in the index.html file reside at
public folder.
But wait you need to paste script below body .
Your final
code look like above file.
Now open
app.js file and change it as below
I am not going to describe each every code in this docs..If anyone need video tutorial
of this project
Kindly Reach at me
Telegram Channel Link : https://t.me/scientificeyeeducation
Whatsapp Group Link : https://chat.whatsapp.com/KBNgnijK4vI5yZ64hAKKOk
Facebook Group : https://www.facebook.com/groups/415952859495530/
Now Your Finalize file as follows :
AddContact.js
import React, { Component } from 'react'
export default class AddContact extends Component {
SubmitContact(event) {
event.preventDefault();
let contact = {
firstName:
this.refs.firstName.value,
lastName:
this.refs.lastName.value,
email:
this.refs.email.value,
}
fetch("http://localhost:8080/api/contacts", {
method
: 'POST',
headers
: {
'content-type': 'application/json',
},
body:
JSON.stringify(contact),
})
.then(response => response.json());
window.location.reload();
}
render() {
return (
<div className="row">
<form className="col s12" onSubmit={this.SubmitContact.bind(this)}>
<div className="row">
<div className="input-field col s6">
<input placeholder="Placeholder" ref="firstName" type="text" className="validate" />
<label htmlFor="firstName">First Name</label>
</div>
<div className="input-field col s6">
<input id="last_name" ref="lastName" type="text" className="validate" />
<label htmlFor="lastName">Last Name</label>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<input id="email" ref="email" type="email" className="validate" />
<label htmlFor="email">Email</label>
</div>
</div>
<div className="row">
<button className="waves-effect waves-light btn" type="submit" name="action">Submit</button>
</div>
</form>
</div>
);
}
}
2. Contact.js File
import React, { Component } from 'react';
import AddContact from './AddContact';
import SingleContact from './SingleContact';
export default class Contact extends Component {
constructor(props) {
super(props);
this.state = {
contacts:
[],
}
}
componentDidMount() {
fetch("http://localhost:8080/api/contacts")
.then(response => console.log('this is ress ',response.json()))
fetch("http://localhost:8080/api/contacts")
.then(response => response.json())
.then(data => this.setState({ contacts: data }))
}
render() {
return (
<div>
<div className="row">
<AddContact />
</div>
<div className="row">
{
this.state.contacts.map(
(item) => (
<SingleContact key={item.id} item={item} />
)
)
}
</div>
</div>
)
}
}
SingleContact.js
import React from 'react';
const SingleContact =({item})=>{
return(
<div className="row">
<div className="col
s12 m6">
<div className="card
blue-grey darken-1">
<div className="card-content
white-text">
<span className="card-title">{item.firstName} {item.lastName}</span>
<p>Contact
me....</p>
</div>
<div className="card-action">
<a href="#">{item.email}</a>
</div>
</div>
</div>
</div>
);
}
export default SingleContact;
App.js File
import logo from './logo.svg';
import Contact from './components/Contact';
import './App.css';
function App()
{
return
(
<div
className="container-fluid">
<nav>
<div
className="nav-wrapper
center-align">
<a
href="/"
className="brand-logo">Contacts</a>
</div>
</nav>
<div
className="row">
<Contact
/>
</div>
</div>
);
}
export default App;
public/index.html
File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico"
/>
<meta name="viewport" content="width=device-width,
initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site
created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json"
/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>
Also Your Spring File As follows
CrmApplication.java
package com.crm.crm;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CrmApplication {
public
static void main(String[] args) {
SpringApplication.run(CrmApplication.class,
args);
}
}
Contact.java
package com.crm.crm.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Data
@Entity
public class Contact {
@Id
@GeneratedValue(strategy
= GenerationType.IDENTITY)
public
Long id;
public
String firstName;
public
String lastName;
public
String email;
public
Contact() {
super();
}
public
Contact(String firstName, String lastName, String email) {
super();
this.firstName
= firstName;
this.lastName
= lastName;
this.email
= email;
}
}
ContactController.java
package com.crm.crm.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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;
@RestController
@RequestMapping(value = "/api")
@CrossOrigin(origins = "http://localhost:3000",methods = {RequestMethod.GET,RequestMethod.POST})
public class ContactController {
@Autowired
private ContactRepository contactRepository;
@GetMapping("/contacts")
public ResponseEntity<?> listOfContacts(){
return ResponseEntity.ok(contactRepository.findAll());
}
@RequestMapping(value = "/contacts",method = RequestMethod.POST)
public ResponseEntity<?> addContact(@RequestBody Contact contact){
Contact addedContact = contactRepository.save(contact);
return ResponseEntity.ok(addedContact);
}
}
ContactRepository.java
package
com.crm.crm.model;
import
org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource
public interface ContactRepository extends CrudRepository<Contact,
Long>{
}
InitialValueLoader.java
package com.crm.crm.model;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import
org.springframework.stereotype.Component;
@Component
public class InitialValueLoader implements
CommandLineRunner {
private
final ContactRepository contactRepository;
@Autowired
public
InitialValueLoader(ContactRepository contactRepository) {
this.contactRepository
= contactRepository;
}
@Override
public
void run(String... args) throws Exception {
contactRepository.save(new
Contact("Praful", "Sonawane",
"prafulsonawane400@gmail.com"));
}
}
Application.properties file :
spring.data.rest.base-path=/api
Now I am attached my pom.xml
file
here
<?xml version="1.0"
encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from
repository -->
</parent>
<groupId>com.crm</groupId>
<artifactId>crm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>crm</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Final
Screenshot Of Project :
Thank you
Praful T. Sonawane
0 Comments