Link API with Spring + Vue.js

Introduction

This time, I created RestAPI with Spring framework and The goal is to display the data in Vue.js. (The environment construction that is the initial setting such as Java installation is omitted.)

Project creation

◇Vue.js We will create it using VueCli.

① Install VueCli from npm

console


npm install -g @vue-cli

② Project creation

console


vue create practice

When executed, the configuration files and sample sources required to create the application will be created automatically. image.png ③ Check the 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 are using "gradle".) image.png

Creating a Rest API

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

Since this time 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 the application is started because it is an in-memory database. Two SQLs are automatically executed at the time of initialization. image.png

data.sql

data.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', 'Human Resources Department');
schema.sql

schema.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 launch it with "Spring Boot App" image.png After startup "http: // localhost: 8080 / h2-console" Go to and make sure the table is created

Select Connect image.png Both tables and data have been created. image.png

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

The fixed value is packed in a List and returned.

PracticeServiceImp.java

PracticeServiceImp.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<String> getAll() {
		List<String> list = new ArrayList<>();
		 
        list.add("1");
        list.add("2");
        list.add("3");
 
		return list;
	}
}

Call Service, pack the acquired value in List, and return it.

PracticeController.java

PracticeController.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 {
	
	private final PracticeService practiceService;
	
	@Autowired
 	public PracticeController(PracticeServiceImp practiceService){
 		this.practiceService = practiceService;
 	}

	@GetMapping
	public List<String> getAll() {
		List<String> list = practiceService.getAll();
		
		return list;
	}
}

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.

(3) Modify to store the value obtained from DB in Form class and return it. The DAO class is responsible for connecting to the DB and issuing SQL. The roles are "Controller (handling of request and response)", "Service (logic)" and "Dao (DB operation)".

PracticeServiceImp.java

PracticeServiceImp.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;
	
	@Autowired
	public PracticeServiceImp(PracticeDao dao) {
		this.dao = dao;
	}
	@Override
	public List<PracticeForm> getAll() {
//		List<PracticeForm> list = new ArrayList<>();
//		 
//        list.add("1");
//        list.add("2");
//        list.add("3");
		return dao.getAll();
	}
}

PracticeController.java

PracticeController.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<PracticeForm> getAll() {
		List<PracticeForm> list = practiceService.getAll();
		
		return list;
	}
}

New file to store data

PracticeForm.java

PracticeForm.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;
	}

}

New file for DB operation

PracticeDaoImp.java

PracticeDaoImp.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<PracticeForm> 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<PracticeForm> list = new ArrayList<PracticeForm>();
		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;
	}

}

After the above correction, try side access. image.png

The value of DB has been acquired.

Run API from Vue.js

Call the API from the front end side and display the data. ① Install axios Use "axios" to execute the API. axios: JavaScript library capable of HTTP communication

console


npm install --save axios

② Call the API with axios.

Home.vue

Home.vue


// Home.vue
<template>
  <div>
    {{ people }}
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      people: []
    }
  },
  methods: {
    getPerson () {
      const path = 'http://localhost:8080/api/practice'
      axios.get(path)
        .then(response => {
          this.people = response.data
        })
        .catch(error => {
          console.log(error)
        })
    }
  },
  created () {
    this.getPerson()
  }
}
</script>

Check the screen. image.png

The data has been acquired.

③ Display on the table Let's process the screen like that using the data table of the UI framework "vuetify"

Person.vue

Person.vue


// Person.vue
<template>
  <div>
    <h1>Employee list</h1>
    <v-data-table
          :headers="headers"
          :items="people">
    </v-data-table>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  components:{

  },
  data () {
    return {
      people: [],
      singleSelect: false,
        selected: [],
        headers: [
          {
            align: 'start',
            sortable: false,
          },
          { text: 'ID', value: 'id' },
          { text: 'Full name', value: 'name' },
          { text: 'Employee code', value: 'code' },
          { text: 'Affiliation name', value: 'belong_nm' },
        ],
    }
  },
  methods: {
    getNews () {
      const path = 'http://localhost:8080/api/practice'
      axios.get(path)
        .then(response => {
          this.people = response.data
        })
        .catch(error => {
          console.log(error)
        })
    }
  },
  created () {
    this.getNews()
  }
}
</script>

By displaying it using a data table, something like that was easily displayed. image.png

Summary

I was able to create a simple API and work it with the front end. Thanks to modern frameworks, where and what kind of logic to write is roughly decided. Therefore, the role is clear and convenient.

References

I was allowed to reference. https://b1tblog.com/2020/03/17/spring-rest-2/

Recommended Posts

Link API with Spring + Vue.js
Spring with Kotorin --4 REST API design
Configure microservices with Spring Cloud (4): API Gateway
Create a web api server with spring boot
Compatible with Android 10 (API 29)
Spring with Kotorin --- 5. Actuator
Self-made Validation with Spring
Spring with Kotorin ―― 1. SPRING INITIALIZR
Download with Spring Boot
Automatically map DTOs to entities with Spring Boot API
Hello World (REST API) with Apache Camel + Spring Boot 2
[Spring Boot] Get user information with Rest API (beginner)
Implement a simple Rest API with Spring Security with Spring Boot 2.0
Customize REST API error response with Spring Boot (Part 2)
I created an api domain with Spring Framework. Part 1
Customize REST API error response with Spring Boot (Part 1)
Attempt to SSR Vue.js with Spring Boot and GraalJS
Hello World with Spring Boot
Java Config with Spring MVC
Create XML-RPC API with Wicket
Test Web API with junit
Implement GraphQL with Spring Boot
Spring with Kotorin --8 Repository layer
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Get started with Spring boot
Implement REST API with Spring Boot and JPA (Application Layer)
Use Bulk API with RestHighLevelClient
Hello World with Spring Boot!
Spring with Kotorin --6 Asynchronous processing
Run LIFF with Spring Boot
API creation with Rails + GraphQL
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Let's make a simple API with EC2 + RDS + Spring boot ①
Spring with Kotorin ―― 7. Service layer
Try hitting the zip code search API with Spring Boot
Using Mapper with Java (Spring)
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
Getting Started with Spring Boot
Implement REST API with Spring Boot and JPA (domain layer)
Create microservices with Spring Boot
Send email with spring boot
Implement a simple Rest API with Spring Security & JWT with Spring Boot 2.0
Implement a simple Web REST API server with Spring Boot + MySQL
Get Flux result of Spring Web Flux from JS with Fetch API
I made a simple search form with Spring Boot + GitHub Search API.
[Beginner] Let's write REST API of Todo application with Spring Boot
Use Basic Authentication with Spring Boot
Implemented authentication function with Spring Security ②
Implement text link with Springboot + Thymeleaf
Automatic API testing with Selenium + REST-Assured
gRPC on Spring Boot with grpc-spring-boot-starter
Implemented authentication function with Spring Security ③
Create an app with Spring Boot 2
Hot deploy with Spring Boot development
Database linkage with doma2 (Spring boot)