Create a web api server with spring boot

Overview

--Create a web api that just returns a string with spring boot

environment

procedure

Create a template with spring initializr

--You can easily create a template of spring boot with spring initializr

  1. Go to https://start.spring.io
  2. Select as follows spring-initializr.png
  1. Select Generate the Project and download the zip
  2. Unzip the zip and place the folder in a suitable location --The folder structure looks like this
.
├── HELP.md
├── README.md
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── example
    │   │           └── api
    │   │               └── ApiApplication.java
    │   └── resources
    │       ├── application.properties
    │       ├── static
    │       └── templates
    └── test
        └── java
            └── com
                └── example
                    └── api
                        └── ApiApplicationTests.java

Intellij IDEA Preferences

--Set up the IDE so that you can edit the zip you just created with Intellij IDEA.

  1. After starting Intellij IDEA, select ʻimport project` and select the folder you just unzipped.
  2. Select gradle from ʻImport project from external model`
  3. Check ʻUse auto import`
  4. Make sure the Gradle JVM is Java 12
  5. Select Finish
  6. In Preference-> Build, Execution, Deployment-> compiler-> annotation processor Check ʻEnable annotation processing` and save
  7. Open the project settings with command +; and open the project settings Select 12 for each of Project SDK and Project language level and save

Check build.gradle

--Project dependencies are defined in build.gradle

build.gradle


plugins {
	id 'org.springframework.boot' version '2.1.7.RELEASE'
	id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

--plugins, ʻapply plugin: Plugin settings -- java: You will be able to perform tasks such as compiling java source code and unit testing. --ʻOrg.springframework.boot: You will be able to perform spring boot tasks such as bootRun. --ʻIo.spring.dependency-management: Provides maven BOM functionality (which resolves dependent library versions) not found in gradle -- group, version: Project settings --suceCompatibility: Specify the version of the JDK used in the project --Change from 1.8 to 12 to use Java 12 this time. -- repositories: Specify the repository to get the dependent libraries --dependencies: Definition of external dependencies. The Spring Web Starter specified in initializr is reflected here. --ʻImplementation: Used at compile time and run time --testImplementation: Used at compile time and run time during testing

Launch application

--Right-click ʻApiApplication` and execute --The following log will be output and Spring boot will start.

23:07:15: Executing task 'ApiApplication.main()'...

> Task :compileJava
> Task :processResources
> Task :classes

> Task :ApiApplication.main()

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.7.RELEASE)

2019-08-06 23:07:32.447  INFO 20662 --- [           main] com.example.api.ApiApplication           : Starting ApiApplication on xxxnoMacBook-Air.local with PID 20662 (/Users/xxx/dev/spring-boot-api/build/classes/java/main started by xxx in /Users/xxx/dev/spring-boot-api)
2019-08-06 23:07:32.452  INFO 20662 --- [           main] com.example.api.ApiApplication           : No active profile set, falling back to default profiles: default
2019-08-06 23:07:35.060  INFO 20662 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-08-06 23:07:35.118  INFO 20662 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-08-06 23:07:35.119  INFO 20662 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.22]
2019-08-06 23:07:35.309  INFO 20662 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-08-06 23:07:35.309  INFO 20662 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2746 ms
2019-08-06 23:07:35.680  INFO 20662 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-08-06 23:07:36.278  INFO 20662 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-08-06 23:07:36.292  INFO 20662 --- [           main] com.example.api.ApiApplication           : Started ApiApplication in 4.996 seconds (JVM running for 5.699)

--Access http: // localhost: 8080 with a browser, and if the following screen is displayed, it is OK. whitelabel-error.png

Creating a Controller

--I created a package called controller and created a class called HelloWorldController under it. --String returns hello world! when a GET request comes in with the path / hello --The method name is getHello, but anything is fine.

HelloWorldController


package com.example.api.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("hello")
public class HelloWorldController {

    @RequestMapping(method = RequestMethod.GET)
    public String getHello() {
        return "hello world!";
    }
}

@RestController

--Annotation attached to Controller class that is the endpoint of REST web api ――The same effect as adding the following two annotations --@Controller: Indicates that it is a controller class of MVC --@ResponseBody: The return value of the method of the given class becomes the response body as it is.

@RequestMapping()

--Annotation that sets the path to access the REST web api --method = RequestMethod.XXX (XXX: GET, POST, etc.) can be assigned to each HTTP method.

Application restart

--Restart the application and access http: // localhost: 8080 / hello in your browser --If hello world! Is displayed on the white screen, it's OK! helloworld.png

Recommended Posts

Create a web api server with spring boot
Create a website with Spring Boot + Gradle (jdk1.8.x)
Create a Spring Boot development environment with docker
Create Spring Cloud Config Server with security with Spring Boot 2.0
Create microservices with Spring Boot
Implement a simple Rest API with Spring Security with Spring Boot 2.0
Create a simple demo site with Spring Security with Spring Boot 2.1
Create an app with Spring Boot 2
Create an app with Spring Boot
Let's make a simple API with EC2 + RDS + Spring boot ①
Implement a simple Rest API with Spring Security & JWT with Spring Boot 2.0
Create a simple web application with Dropwizard
Create a simple on-demand batch with Spring Batch
Start web application development with Spring Boot
Run WEB application with Spring Boot + Thymeleaf
Create a simple web server with the Java standard library com.sun.net.httpserver
Let's make a book management web application with Spring Boot part1
Let's make a book management web application with Spring Boot part3
Let's make a book management web application with Spring Boot part2
I made a simple search form with Spring Boot + GitHub Search API.
Create a Spring Boot app development project with the cURL + tar command
Spring Boot2 Web application development with Visual Studio Code SQL Server connection
Create a Spring Boot application using IntelliJ IDEA
Create CRUD apps with Spring Boot 2 + Thymeleaf + MyBatis
How to create a server executable JAR and WAR with Spring gradle
Create your own Utility with Thymeleaf with Spring Boot
Create Spring Boot environment with Windows + VS Code
Build a WEB system with Spring + Doma + H2DB
Download with Spring Boot
[Spring Boot] Precautions when developing a web application with Spring Boot and placing war on an independent Tomcat server
I tried to clone a web application full of bugs with Spring Boot
Create a portfolio app using Java and Spring Boot
Build a WEB system with Spring + Doma + H2DB + Thymeleaf
Hello World (REST API) with Apache Camel + Spring Boot 2
[Spring Boot] Get user information with Rest API (beginner)
[JUnit 5 compatible] Write a test using JUnit 5 with Spring boot 2.2, 2.3
[Spring Boot] How to create a project (for beginners)
Customize REST API error response with Spring Boot (Part 2)
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
A memorandum when creating a REST service with Spring Boot
Create Restapi with Spring Boot ((1) Until Run of App)
Customize REST API error response with Spring Boot (Part 1)
I wrote a test with Spring Boot + JUnit 5 now
Create API key authentication for Web API in Spring Security
Build a WEB system with Spring + Doma + H2DB Part 2
Generate barcode with Spring Boot
Hello World with Spring Boot
Create XML-RPC API with Wicket
Test Web API with junit
Implement GraphQL with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
[Spring Boot] Web application creation
File upload with Spring Boot
Spring Boot starting with copy
Create a playground with Xcode 12
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot