[Java] Coordinating API with Spring+Vue.js

4 minute read

Introduction

This time, create RestAPI with Spring framework, The goal is to display the data with Vue.js. (The initial environment setup such as Java installation is omitted.)

Project creation

◇Vue.js

I will create it using VueCli.

① Install VueCli from npm

console


npm install -g @vue-cli

② Project creation

console


vue create practice

When you execute it, the configuration files and sample sources required to create the application will be created automatically. image.png ③Check sample screen Execute the following under the created project

console


npm run serve

image.png

◇ Spring

We will proceed using “Spring Tools for Eclipse”.

① Project creation Select “Spring Starter Project” to create a project

image.png

When you create a project, the following folders and files will be created. (This time, we use “gradle”.) image.png

Creating Rest API

Create API to get data from H2 database. ① H2 database preparation What is the H2 database? Open source RDB on JAVA platform It can be used as an “in-memory database”, and it comes with Spring boot by default, so no complicated settings are required. The following JDBC drivers are already registered image.png

This time, since it will be used as an “in-memory database”, we will create tables and data to be initialized. Place “data.sql” and “schema.sql” under “src/main/resources”. It is initialized every time when the application starts because it is an in-memory database. Two SQLs are automatically executed at initialization. image.png

data.sql
#### **`data.sql`** ```sql INSERT INTO person(code, name, belong_nm) VALUES('001','Test 1','General Affairs Department'); INSERT INTO person(code, name, belong_nm) VALUES('002','Test 2','HR'); ```
schema.sql
#### **`schema.sql`** ```sql CREATE TABLE person ( id INT NOT NULL AUTO_INCREMENT, code VARCHAR(100) NOT NULL, name VARCHAR(100) NOT NULL, belong_nm VARCHAR(500) NOT NULL, PRIMARY KEY(id) ); ```

Right click on the project and start with “Spring Boot App” image.png After starting “http://localhost:8080/h2-console” And check that the table has been created

Select Connect image.png Tables and data are created. image.png

② Create Controller and Service Call Service from Controller. Do not refer to the DB once and return a fixed value.

Fixed value is packed in List and returned. </div></details>

PracticeServiceImp.java
#### **`PracticeServiceImp.java`** ```java package com.example.demo.service; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; @Service public class PracticeServiceImp implements PracticeService { @Override public List getAll() { List list = new ArrayList<>(); It's a sequel. list.add("1"); list.add("2"); list.add("3"); return list; } } ``` </div></details> Call Service, fill the acquired value in a List and return it. </div></details>
PracticeController.java
#### **`PracticeController.java`** ```java package com.example.demo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demo.service.PracticeService; import com.example.demo.service.PracticeServiceImp; @RestController @RequestMapping("api/practice") public class PracticeController { It's a sequel. private final PracticeService practiceService; It's a sequel. @Autowired public PracticeController(PracticeServiceImp practiceService){ this.practiceService = practiceService; } @GetMapping public List getAll() { List list = practiceService.getAll(); It's a sequel. return list; } } ``` </div></details> We will actually execute it and check it. ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/567766/31ef2fd9-f158-ce3b-980f-234a77b68ab6.png) "Http://localhost:8080/api/practice" I accessed and the fixed value was displayed. ③ Store the value acquired from DB in Form class and modify so that it returns It is up to the DAO class to connect to the DB and issue SQL. "Controller (request and response handling)" "Service (logic)" "Dao (DB operation)" is the role.
PracticeServiceImp.java
#### **`PracticeServiceImp.java`** ```java package com.example.demo.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.demo.dao.PracticeDao; import com.example.demo.form.PracticeForm; @Service public class PracticeServiceImp implements PracticeService { private final PracticeDao dao; It's a sequel. @Autowired public PracticeServiceImp(PracticeDao dao) {this.dao = dao; } @Override public List getAll() { // List list = new ArrayList<>(); // // list.add("1"); // list.add("2"); // list.add("3"); return dao.getAll(); } } ``` </div></details>
PracticeController.java
#### **`PracticeController.java`** ```java package com.example.demo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demo.form.PracticeForm; import com.example.demo.service.PracticeService; import com.example.demo.service.PracticeServiceImp; @RestController @RequestMapping("api/practice") @CrossOrigin(origins = {"http://localhost:8081"}) public class PracticeController { private final PracticeService practiceService; @Autowired public PracticeController(PracticeServiceImp practiceService){ this.practiceService = practiceService; } @GetMapping public List getAll() { List list = practiceService.getAll(); return list; } } ``` </div></details> データを格納するための新規ファイル
PracticeForm.java
#### **`PracticeForm.java`** ```java package com.example.demo.form; import javax.validation.constraints.NotNull; public class PracticeForm { public PracticeForm() {}; public PracticeForm(int id, String code, String name, String belong_nm) { super(); this.id = id; this.code = code; this.name = name; this.belong_nm = belong_nm; } @NotNull private int id; @NotNull private String code; @NotNull private String name; @NotNull private String belong_nm; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBelong_nm() { return belong_nm; } public void setBelong_nm(String belong_nm) { this.belong_nm = belong_nm; } } ```
DB操作するための新規ファイル
PracticeDaoImp.java
#### **`PracticeDaoImp.java`** ```java package com.example.demo.dao; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.example.demo.form.PracticeForm; @Repository public class PracticeDaoImp implements PracticeDao { private final JdbcTemplate jdbcTemplate; @Autowired public PracticeDaoImp(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public List getAll() { // TODO Auto-generated method stub String sql = "select id, code, name, belong_nm from person"; List<Map<String, Object>> resultList = jdbcTemplate.queryForList(sql); List list = new ArrayList(); for(Map<String, Object> result : resultList) { PracticeForm practiceForm = new PracticeForm(); practiceForm.setId((int)result.get("id")); practiceForm.setCode((String)result.get("code")); practiceForm.setName((String)result.get("name")); practiceForm.setBelong_nm((String)result.get("belong_nm")); list.add(practiceForm); } return list; } } ``` </div></details> 上記修正後、サイドアクセスしてみます。 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/567766/308452e4-1d31-f14b-6dfb-4cfbc69312fa.png) DBの値が取得できております。 ## Vue.jsからAPIを実行 フロントエンド側からAPIを呼び出しデータを表示させます。 ①axiosをインストール APIを実行するために「axios」を使用します。 axios:HTTP通信が可能なJavaScriptのライブラリ #### **`コンソール`** ```console npm install --save axios ``` ②axiosでAPIを呼び出す。 ※VueもSpringもサーバーを起動させておく。 axiosにて、APIのURLを指定しデータを取得する。
Home.vue
#### **`Home.vue`** ```vue // Home.vue ```
画面を確認する。 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/567766/1cb7cee7-5317-ab5c-50a7-40789bd9b669.png) データが取得されました。 ③テーブルに表示させる UIフレームワーク「vuetify」のデータテーブルを用いて、画面をそれっぽく加工してみます
Person.vue
#### **`Person.vue`** ```vue // Person.vue ```
By displaying it using a data table, something like that was easily displayed. ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/567766/785bc445-3ce1-e3ec-078c-ccceb8aa049f.png) ## Summary I was able to create a simple API and integrate it with the front end. Thanks to modern frameworks, it is generally decided where and what logic is written. Therefore, the role is clear and convenient. ## References I was allowed to reference. https://b1tblog.com/2020/03/17/spring-rest-2/