webjava前端和后端交互
目录
web+java前端和后端交互
前言
#创作灵感#
·学习
准备:基于前两次文章( )( )
对于文章2要检测数据,可自行下载 postman 进行检测,网上均有教程
前后端交互 知识框架梳理: html(js) -> ajax -> springboot 接口- > java代码 ->mysql
注意:本次交互是把前端代码文件引入到IDEA文件中。
RESTful API :基于HTTP协议,通过定义标准的URL和HTTP请求方法(如GET、POST、PUT等)进行数据交互。
1.前端代码准备
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数据管理系统</title>
<style>
/* Reset some browser default styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
/*background-color: #f5f5f5;*/
color: #333;
background-color: skyblue;
}
.container {
max-width: 800px;
margin: 50px auto;
padding: 20px;
background-color: white;
box-shadow: 0 4px 6px rgba(10, 0, 0, 0.1);
border-radius: 8px;
}
h1 {
text-align: center;
margin-bottom: 20px;
}
form {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
margin-bottom: 20px;
}
label {
font-weight: bold;
}
input[type="number"],
input[type="text"] {
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
#addBtn,
#updateBtn {
grid-column: span 2;
background-color: #4CAF50;
color: white;
}
#updateBtn {
background-color: #FFC107;
}
button:hover {
/*background-color: darken(#4CAF50, 10%);*/
}
#dataTable {
width: 100%;
border-collapse: collapse;
}
#dataTable th,
#dataTable td {
padding: 10px;
border: 1px solid #ddd;
}
#dataTable th {
background-color: #eee;
font-weight: bold;
}
#dataTable tr:nth-child(even) {
background-color: #f2f2f2;
}
#dataTable button {
padding: 5px 10px;
margin: 0 5px;
font-size: 12px;
}
#dataTable .edit {
background-color: #2196F3;
color: white;
}
#dataTable .delete {
background-color: #F44336;
color: white;
}
#dataTable button:hover {
filter: brightness(0.9);
}
</style>
</head>
<body>
<div class="container">
<h1>数据管理系统</h1>
<form id="dataForm">
<label for="id">ID:</label>
<input type="number" id="id" name="id" disabled>
<label for="name">名字</label>
<input type="text" id="name" name="name">
<label for="age">年龄</label>
<input type="number" id="age" name="age">
<label for="gender">性别</label>
<input type="text" id="gender" name="gender">
<button type="button" id="addBtn">添加</button>
<button type="button" id="updateBtn" disabled>更新</button>
</form>
<button onclick="fetchData()" style="margin: auto;background-color: hotpink">一键获取数据</button>
<table id="dataTable">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>操作</th>
</tr>
</thead>
<tbody id="dataBody">
</tbody>
</table>
</div>
<script>
const dataBody = document.getElementById('dataBody');
const addBtn = document.getElementById('addBtn');
const updateBtn = document.getElementById('updateBtn');
const idInput = document.getElementById('id');
const nameInput = document.getElementById('name');
const ageInput = document.getElementById('age');
const genderInput = document.getElementById('gender');
// Fetch all data initially 最初获取所有数据
fetchData();
// Event listeners 事件监听器
addBtn.addEventListener('click', addData);
updateBtn.addEventListener('click', updateData);
dataBody.addEventListener('click', handleActionClick);
// Fetch data from the server 从服务器获取数据
function fetchData() {
fetch('/users')
.then(response => response.json())
.then(data => {
dataBody.innerHTML = '';
data.data.forEach(item => {
const row = `
<tr>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.age}</td>
<td>${item.gender}</td>
<td>
<button class="edit">编辑</button>
<button class="delete">删除</button>
</td>
</tr>
`;
dataBody.insertAdjacentHTML('beforeend', row);
});
});
}
// Add new data to the server
function addData() {
const data = {
id: generateId(),
name: nameInput.value,
age: ageInput.value,
gender: genderInput.value
};
fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(() => fetchData())
.catch(error => console.error('Error:', error));
clearForm();
}
// Update existing data on the server
function updateData() {
const data = {
id: idInput.value,
name: nameInput.value,
age: ageInput.value,
gender: genderInput.value
};
fetch(`/users/${data.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(() => fetchData())
.catch(error => console.error('Error:', error));
}
// Delete data from the server
function deleteData(id) {
fetch(`/users/${id}`, {
method: 'DELETE'
})
.then(() => fetchData())
.catch(error => console.error('Error:', error));
}
// Handle edit and delete button clicks 处理编辑和删除按钮点击
function handleActionClick(event) {
if (event.target.classList.contains('edit')) {
const row = event.target.closest('tr');
const cells = row.getElementsByTagName('td');
idInput.value = cells[0].textContent;
nameInput.value = cells[1].textContent;
ageInput.value = cells[2].textContent;
genderInput.value = cells[3].textContent;
enableForm();
} else if (event.target.classList.contains('delete')) {
const row = event.target.closest('tr');
const id = row.getElementsByTagName('td')[0].textContent;
deleteData(id);
}
}
// Enable editing of the form 启用表单编辑
function enableForm() {
idInput.removeAttribute('disabled');
nameInput.disabled = false;
ageInput.disabled = false;
genderInput.disabled = false;
addBtn.disabled = true;
updateBtn.disabled = false;
}
// Disable editing of the form 禁用表单编辑
function disableForm() {
idInput.setAttribute('disabled', '');
nameInput.disabled = true;
ageInput.disabled = true;
genderInput.disabled = true;
addBtn.disabled = false;
updateBtn.disabled = true;
}
// Clear the form fields 清除表单字段
function clearForm() {
idInput.value = '';
nameInput.value = '';
ageInput.value = '';
genderInput.value = '';
disableForm();
}
// Generate a unique ID 生成唯一ID
function generateId() {
return Math.floor(Math.random() * 100000);
}
</script>
</body>
</html>
注意注意注意!!!!
fetch后面的接口要和后端
接口一致
2.文件引入后端文件
######## 启动后端 #####
在浏览器输入 //
填你在application.properties所填的端口号,后面的 test4 是html文件名,填你的
3.效果
可对数据进行增删改查
下次讲前后端分离,前端通过
axios 向后端请求数据