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.)
◇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. ③ Check the sample screen Execute the following under the created project
console
npm run serve
◇Spring We will proceed using "Spring Tools for Eclipse".
① Project creation Select "Spring Starter Project" to create a project
When you create a project, the following folders and files will be created. (This time, we are using "gradle".)
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
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.
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
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" After startup "http: // localhost: 8080 / h2-console" Go to and make sure the table is created
Select Connect Both tables and data have been created.
② 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
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
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;
}
}
「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
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
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
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
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.
The value of DB has been acquired.
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
<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.
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
<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.
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.
I was allowed to reference. https://b1tblog.com/2020/03/17/spring-rest-2/
Recommended Posts