PIXNET Logo登入

spring boot rest

跳到主文

REST API is today's requirements for Mobile Apps, Web Application or Desktop Application that need to connect with Database. That's why we need to create a step by step tutorial of building Java REST API server using Spring Boot and MongoDB. The data store in MongoDB server and accessible everywhere via Java REST API. Previously, we have to create REST API in different technology and framework using Grails and Node.js. Now, we are using Spring Boot for it. After all, you can compare which technology or framework that fits your needs. 1. Generate a New Spring Boot Gradle Project We assume that you have installed JDK 8, Gradle and IDE (Netbeans, Eclipse, STS or IntellijIdea). Next, we will create a new Spring Boot Gradle project using Spring Initializer. Just go to Spring Initializr web-based Spring project generator then fill the required frameworks and libraries. After filling all fields, click Generate Project. It will automatically download the zipped project. Next, extract the zipped project to your java projects folder. On the project folder root, you will find `build.gradle` file for register dependencies, initially it looks like this. buildscript { ext { springBootVersion = '1.5.7.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.spring' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-data-mongodb') compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') } Open other terminal then run MongoDB server. In current terminal go to newly extracted Spring Boot project folder then type this command to compile the application. ./gradlew compile Open and edit `src/resources/application.properties` then add this lines of strings. spring.data.mongodb.database=springmongodb spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 2. Create Model or Entity Class We are not accessing directly to MongoDB collections and fields but we have to access it via Java Object. For that, we have to create a new Java Class as a model or entity. If you are using Netbeans (similar with some IDE), right-click project name then click `New` then click `Java Class`. Fill necessary fields like above screenshot then click Finish button. Netbeans will automatically open the newly created file, replace all codes with this. package com.spring.restapi.models; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "products") public class Product { @Id String id; String prodName; String prodDesc; Double prodPrice; String prodImage; public Product() { } public Product(String prodName, String prodDesc, Double prodPrice, String prodImage) { this.prodName = prodName; this.prodDesc = prodDesc; this.prodPrice = prodPrice; this.prodImage = prodImage; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getProdName() { return prodName; } public void setProdName(String prodName) { this.prodName = prodName; } public String getProdDesc() { return prodDesc; } public void setProdDesc(String prodDesc) { this.prodDesc = prodDesc; } public Double getProdPrice() { return prodPrice; } public void setProdPrice(Double prodPrice) { this.prodPrice = prodPrice; } public String getProdImage() { return prodImage; } public void setProdImage(String prodImage) { this.prodImage = prodImage; } } That product class mapping to products collections of MongoDB which has 5 fields (id, prodName, prodDesc, prodPrice, prodImage). Each field has getter and setter. 3. Create a New Repository Interface for Product Model Now, we need to create an interface for connecting Product model and controller. On Netbeans right-click project name on projects left panel then choose `New` then choose `Java Interface`. Fill necessary fields like above screenshot then click Finish button. Netbeans will automatically open the new `ProductRepository.java` interface file. Replace all codes with this. package com.spring.restapi.repositories; import com.spring.restapi.models.Product; import org.springframework.data.repository.CrudRepository; public interface ProductRepository extends CrudRepository { @Override Product findOne(String id); @Override void delete(Product deleted); } We only add `findOne` and `delete` method to the interface because the rest method already handled by `CrudRepository` of Spring Data MongoDB. 4. Create a New RESTful Controller for Accessing Product Data Now, it's a time for RESTful Web Service (REST API) implementation by creating a new RESTful controller file. On the Netbeans right-click project name then click `New` then click `Java Class` again. Fill necessary fields like above screen shot then click Finish button. Netbeans will automatically open the new `ProductController.java` class file. Replace all codes with this. package com.spring.restapi.controllers; import com.spring.restapi.models.Product; import com.spring.restapi.repositories.ProductRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; 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 public class ProductController { @Autowired ProductRepository productRepository; @RequestMapping(method=RequestMethod.GET, value="/products") public Iterable product() { return productRepository.findAll(); } @RequestMapping(method=RequestMethod.POST, value="/products") public String save(@RequestBody Product product) { productRepository.save(product); return product.getId(); } @RequestMapping(method=RequestMethod.GET, value="/products/{id}") public Product show(@PathVariable String id) { return productRepository.findOne(id); } @RequestMapping(method=RequestMethod.PUT, value="/products/{id}") public Product update(@PathVariable String id, @RequestBody Product product) { Product prod = productRepository.findOne(id); if(product.getProdName() != null) prod.setProdName(product.getProdName()); if(product.getProdDesc() != null) prod.setProdDesc(product.getProdDesc()); if(product.getProdPrice() != null) prod.setProdPrice(product.getProdPrice()); if(product.getProdImage() != null) prod.setProdImage(product.getProdImage()); productRepository.save(prod); return prod; } @RequestMapping(method=RequestMethod.DELETE, value="/products/{id}") public String delete(@PathVariable String id) { Product product = productRepository.findOne(id); productRepository.delete(product); return "product deleted"; } } 5.Run and Test the Spring Boot MongoDB RESTful Web Service For testing purpose, we use curl from terminal or command line. Let's start the server by type this command. ./gradlew bootRun Open another terminal tab then type this command for post data to REST API. curl -i -X POST -H "Content-Type: application/json" -d '{"prodName":"Dummy Product 1","prodDesc":"The Fresh Dummy Product in The world part 1","prodPrice":100,"prodImage":"https://dummyimage.com/600x400/000/fff"}' localhost:8080/products You will see the successful response like this. HTTP/1.1 200 Content-Type: text/plain;charset=UTF-8 Content-Length: 24 Date: Sun, 17 Sep 2017 10:14:39 GMT 59be4b0fb1a2416a11a43c21 To get all product data type this command. curl -i -H "Accept: application/json" localhost:8080/products You will see all data as JSON array like this. HTTP/1.1 200 Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Sun, 17 Sep 2017 10:17:08 GMT [{"id":"59be4b0fb1a2416a11a43c21","prodName":"Dummy Product 1","prodDesc":"The Fresh Dummy Product in The world part 1","prodPrice":100.0,"prodImage":"https://dummyimage.com/600x400/000/fff"}] To get single data, type this command. curl -i -H "Accept: application/json" localhost:8080/products/59be4b0fb1a2416a11a43c21 You will see the single object of JSON data. HTTP/1.1 200 Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Sun, 17 Sep 2017 10:17:08 GMT {"id":"59be4b0fb1a2416a11a43c21","prodName":"Dummy Product 1","prodDesc":"The Fresh Dummy Product in The world part 1","prodPrice":100.0,"prodImage":"https://dummyimage.com/600x400/000/fff"} To update the specific data by ID type this command. curl -i -X PUT -H "Content-Type: application/json" -d '{"prodPrice":220}' You will see this response on successful update. HTTP/1.1 200 Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Sun, 17 Sep 2017 10:26:08 GMT {"id":"59be4b0fb1a2416a11a43c21","prodName":"Dummy Product 1","prodDesc":"The Fresh Dummy Product in The world part 1","prodPrice":220.0,"prodImage":"https://dummyimage.com/600x400/000/fff"} To delete specific data by ID, type this command. curl -i -X DELETE localhost:8080/products/59be4b0fb1a2416a11a43c21 You will see this response if successful delete. HTTP/1.1 200 Content-Type: text/plain;charset=UTF-8 Content-Length: 15 Date: Sun, 17 Sep 2017 10:28:38 GMT product deleted Resources: https://www.linkedin.com/pulse/spring-boot-rest-api-example-billgate-william/

部落格全站分類:

  • 相簿
  • 部落格
  • 留言
  • 名片
  • 5月 14 週一 201821:24
  • How to Build AngularJS App with Standard Architecture

 

Simple AngularJS application with Yahoo Weather API
After lot of ground work now we can easily start writing our AngularJS application. Let me just give you a brief about what you are going to build. We are going to develop a simple weather forecasting application with Yahoo API. There will be only one screen with one input box, you can enter zip code to see forecast of next 5 days. I am going to use Yahoo weather API to get forecasting data.

So let’s start writing body of index.html.
<body ng-app="myApp" ng-controller="listCtrl">
<center>
<div>
Weather Forecast - Enter zip code and click get forecast
</div>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div ng-view></div>
<hr/>
<div>Angular seed app: v<span app-version></span></div>
</center>
<!-- In production use: <script src="//ajax.googleapis.com/ajax/libs/angularjs/x.x.x/angular.min.js"></script>-->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="list/listController.js"></script>
<script src="components/version/version.js"></script>
<script src="components/version/version-directive.js"></script>
<script src="components/version/interpolate-filter.js"></script>
<script src="services/listService.js"></script>
</body>
Explanation
Observe above HTML properly and you will notice few new attributes starting with ng-

These are angular directives which informs AngularJS framework which DOM element to bind a mentioned behavior. For now let’s continue with the same example and you will understand the purpose of the directive.

Details of angular directives used in above markup are;

(繼續閱讀...)
文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣(5)

  • 個人分類:
▲top
  • 5月 14 週一 201821:24
  • How to Build AngularJS App with Standard Architecture

 

Simple AngularJS application with Yahoo Weather API
After lot of ground work now we can easily start writing our AngularJS application. Let me just give you a brief about what you are going to build. We are going to develop a simple weather forecasting application with Yahoo API. There will be only one screen with one input box, you can enter zip code to see forecast of next 5 days. I am going to use Yahoo weather API to get forecasting data.

So let’s start writing body of index.html.
<body ng-app="myApp" ng-controller="listCtrl">
<center>
<div>
Weather Forecast - Enter zip code and click get forecast
</div>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div ng-view></div>
<hr/>
<div>Angular seed app: v<span app-version></span></div>
</center>
<!-- In production use: <script src="//ajax.googleapis.com/ajax/libs/angularjs/x.x.x/angular.min.js"></script>-->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="list/listController.js"></script>
<script src="components/version/version.js"></script>
<script src="components/version/version-directive.js"></script>
<script src="components/version/interpolate-filter.js"></script>
<script src="services/listService.js"></script>
</body>
Explanation
Observe above HTML properly and you will notice few new attributes starting with ng-

These are angular directives which informs AngularJS framework which DOM element to bind a mentioned behavior. For now let’s continue with the same example and you will understand the purpose of the directive.

Details of angular directives used in above markup are;

(繼續閱讀...)
文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣(0)

  • 個人分類:
▲top
  • 5月 12 週六 201821:11
  • Modules & Controllers in AngularJs

First thing first, let’s start with the main objective of this post. Do not worry when you will complete this blog, you will have an intermediate level of expertise on AngularJS modules & controllers. 

In the  previous AngularJS Tutorial, titled Data-binding in AngularJS, you might have noticed  the source code similar to the one mentioned  below:

angular.module(name, [requires], [configFn]);

Parameter
name: name of the module.
requires:  is an optional parameter, if mentioned the new module get created. If not, an existing module is being retrieved.
configFn:  is an optional parameter, execute function on module load

The universal way to create or register the module with Angular is Parameter. It has a suite of services, controllers, services, configuration & directives. In other words, you can consider it as a main() function to initialize and get chained with variable and methods for an application. 

(繼續閱讀...)
文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣(0)

  • 個人分類:angular
▲top
  • 5月 12 週六 201821:11
  • Modules & Controllers in AngularJs

First thing first, let’s start with the main objective of this post. Do not worry when you will complete this blog, you will have an intermediate level of expertise on AngularJS modules & controllers. 

In the  previous AngularJS Tutorial, titled Data-binding in AngularJS, you might have noticed  the source code similar to the one mentioned  below:

angular.module(name, [requires], [configFn]);

Parameter
name: name of the module.
requires:  is an optional parameter, if mentioned the new module get created. If not, an existing module is being retrieved.
configFn:  is an optional parameter, execute function on module load

The universal way to create or register the module with Angular is Parameter. It has a suite of services, controllers, services, configuration & directives. In other words, you can consider it as a main() function to initialize and get chained with variable and methods for an application. 

(繼續閱讀...)
文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣(2)

  • 個人分類:angular
▲top
  • 5月 11 週五 201821:14
  • Hibernate many to many jointable example

Mapping shows how two entities are related to each other. In many to many mapping many entities of class A can only have multiple entities in class B. Like for example suppose the two classes are Student and Courses. So if these two classes have many to many relationship then it means that each Student can have multiple Courses .And each Course can have multiple students

We will explain this with the help of an example:

We make two class Student(We named the class Stu3 but we will reference it as Student to make it more easy to understand) and Course.

Listing 1: Course class

package model;
 
 import java.io.Serializable;
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.GeneratedValue;
 import javax.persistence.Id;
 
 /**
 *
 * @author Anurag
 */
 @Entity
 public class Course implements Serializable {
 
 @Id
 @GeneratedValue
 @Column(name = "C_ID")
 private Long id;
 private String name;
 private int duration;
 
 public Course() {
 }
 
 public Long getId() {
 return id;
 }
 
 public void setId(Long id) {
 this.id = id;
 }
 
 public Course(String n, int dur) {
 name = n;
 duration = dur;
 }
 
 public int getDuration() {
 return duration;
 }
 
 public void setDuration(int duration) {
 this.duration = duration;
 }
 
 public String getName() {
 return name;
 }
 
 public void setName(String name) {
 this.name = name;
 }
 }
 

(繼續閱讀...)
文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣(8)

  • 個人分類:hibernate
▲top
  • 5月 11 週五 201821:14
  • Hibernate many to many jointable example

Mapping shows how two entities are related to each other. In many to many mapping many entities of class A can only have multiple entities in class B. Like for example suppose the two classes are Student and Courses. So if these two classes have many to many relationship then it means that each Student can have multiple Courses .And each Course can have multiple students

We will explain this with the help of an example:

We make two class Student(We named the class Stu3 but we will reference it as Student to make it more easy to understand) and Course.

Listing 1: Course class

package model;
 
 import java.io.Serializable;
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.GeneratedValue;
 import javax.persistence.Id;
 
 /**
 *
 * @author Anurag
 */
 @Entity
 public class Course implements Serializable {
 
 @Id
 @GeneratedValue
 @Column(name = "C_ID")
 private Long id;
 private String name;
 private int duration;
 
 public Course() {
 }
 
 public Long getId() {
 return id;
 }
 
 public void setId(Long id) {
 this.id = id;
 }
 
 public Course(String n, int dur) {
 name = n;
 duration = dur;
 }
 
 public int getDuration() {
 return duration;
 }
 
 public void setDuration(int duration) {
 this.duration = duration;
 }
 
 public String getName() {
 return name;
 }
 
 public void setName(String name) {
 this.name = name;
 }
 }
 

(繼續閱讀...)
文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣(0)

  • 個人分類:hibernate
▲top
  • 5月 09 週三 201817:44
  • PURPOSE OF LEARN PROGRAMMING

The important piece of all this is that these these are all people without a technical background.

They come from careers where software was not a large part of their job. The need for learning software from a more human focused vantage point is clear.

It is likely that college will persist as the place to learn deeply technical things and bootcamps will be the place to dip your toes in the water.

Everything about computers that exists today was created by humans. It’s all a product of our imaginations and hard work. We have the tools for anyone to learn it.

The path to becoming a programmer is simple. You start at a point on the spectrum where you feel most comfortable and you work your way towards the middle.

(繼續閱讀...)
文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣(0)

  • 個人分類:java
▲top
  • 5月 09 週三 201817:44
  • PURPOSE OF LEARN PROGRAMMING

The important piece of all this is that these these are all people without a technical background.

They come from careers where software was not a large part of their job. The need for learning software from a more human focused vantage point is clear.

It is likely that college will persist as the place to learn deeply technical things and bootcamps will be the place to dip your toes in the water.

Everything about computers that exists today was created by humans. It’s all a product of our imaginations and hard work. We have the tools for anyone to learn it.

The path to becoming a programmer is simple. You start at a point on the spectrum where you feel most comfortable and you work your way towards the middle.

(繼續閱讀...)
文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣(4)

  • 個人分類:java
▲top
  • 4月 17 週二 201814:44
  • Learn Java Programming Language

If you are planning for Java certification, here is a Java certification path for you to give the best shot at the right time. For top organizations, certification is taken as the proof of knowledge that showcases your skills to the outer world.

Oracle is the most desirable certification and usually preferred by software developers around the world. This would not be saying wrong that Java certification keeps you ahead of the crowd when you apply for Java jobs in the technical marketplace.

First of all, you need to be sure on latest Java version. Java 9 is the most recent version that completely focuses on the modularization concept to speed up overall execution and implementation time.

The best idea is to start with Java SE 9 certification that covers all basic concepts of Java and OOPs. You would get complete details of the certification on the Oracle site with examples and topics included in the certification.

To get the certification, you need to understand each and every concept of Java deeply. Once you are sure on the basics, then you can opt for advance certification too, like Java EE certification and many others.

(繼續閱讀...)
文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣(0)

  • 個人分類:java
▲top
  • 4月 17 週二 201814:44
  • Learn Java Programming Language

If you are planning for Java certification, here is a Java certification path for you to give the best shot at the right time. For top organizations, certification is taken as the proof of knowledge that showcases your skills to the outer world.

Oracle is the most desirable certification and usually preferred by software developers around the world. This would not be saying wrong that Java certification keeps you ahead of the crowd when you apply for Java jobs in the technical marketplace.

First of all, you need to be sure on latest Java version. Java 9 is the most recent version that completely focuses on the modularization concept to speed up overall execution and implementation time.

The best idea is to start with Java SE 9 certification that covers all basic concepts of Java and OOPs. You would get complete details of the certification on the Oracle site with examples and topics included in the certification.

To get the certification, you need to understand each and every concept of Java deeply. Once you are sure on the basics, then you can opt for advance certification too, like Java EE certification and many others.

(繼續閱讀...)
文章標籤

saravanagumar 發表在 痞客邦 留言(0) 人氣(2)

  • 個人分類:java
▲top
«123»

個人資訊

saravanagumar
暱稱:
saravanagumar
分類:
好友:
累積中
地區:

個人資訊

saravanagumar
暱稱:
saravanagumar
分類:
好友:
累積中
地區:

熱門文章

  • ()Spring boot rest
  • ()create spring boot web application project
  • ()java training for oracle certification
  • ()Learn Java Programming Language
  • ()PURPOSE OF LEARN PROGRAMMING
  • ()Hibernate many to many jointable example
  • ()Modules & Controllers in AngularJs
  • ()How to Build AngularJS App with Standard Architecture
  • ()Hibernate Many to Many Relationship
  • ()Spring-boot integrated Rabbitmq

熱門文章

  • ()Spring boot rest
  • ()create spring boot web application project
  • ()java training for oracle certification
  • ()Learn Java Programming Language
  • ()PURPOSE OF LEARN PROGRAMMING
  • ()Hibernate many to many jointable example
  • ()Modules & Controllers in AngularJs
  • ()How to Build AngularJS App with Standard Architecture
  • ()Hibernate Many to Many Relationship
  • ()Spring-boot integrated Rabbitmq

文章分類

  • spring boot (0)
  • java (0)
  • hibernate (0)
  • angular (0)
  • spring (0)
  • spring boot (0)
  • java (0)
  • hibernate (0)
  • angular (0)
  • spring (0)
  • 未分類文章 (1)

文章分類

  • spring boot (0)
  • java (0)
  • hibernate (0)
  • angular (0)
  • spring (0)
  • spring boot (0)
  • java (0)
  • hibernate (0)
  • angular (0)
  • spring (0)
  • 未分類文章 (1)

最新文章

    最新文章

      動態訂閱

      動態訂閱

      文章精選

      文章精選

      文章搜尋

      文章搜尋

      誰來我家

      誰來我家

      參觀人氣

      • 本日人氣:
      • 累積人氣:

      參觀人氣

      • 本日人氣:
      • 累積人氣: