因为代码写得少,学的前端很杂,后端学得少,最近写后端,学到了一些东西。
开始记录
**SpringBoot+Mybatis+mySQL+Ajax实现前后端数据交互**
问题:要干什么?
实现前后端数据的交互,当前端带参数(或不带参数)向后端发送请求之后,后端能从数据库中的数据“操作”(增删改查)后返回给前端页面。
传递的数据类型是json
前端收到后端传来的json数据后可以对将json对象中的数据整合到html标签中,直接显示当前的一个后者使用遍历。
后端收到前端的数据可以对数据库进行增删改查。
(一)数据库
- 创建数据库和数据表并插入数据
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`msg` varchar(255) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('1', '林一一', '业精于勤荒于嬉,行成于思毁于随');
INSERT INTO `t_user` VALUES ('2', '一一林', '今天的自信源自昨天的踏实努力');
(二)SpringBoot的搭建
1.创建项目
2. 勾选依赖
pom.xml (可以CV后使用)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>ajax</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ajax</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
(三)整合Mybatis
server:
port: 8099
spring:
#数据源,连接到springbootajax数据库
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springbootajax
username: root
password:
mvc:
view:
prefix:
classpaths: /templates
suffix: .html
mybatis:
#扫描实体类的包
type-aliases-package: com.example.ajax.pojo
#ָ指定myBatis的核心配置文件与Mapper映射文件
mapper-locations: classpath:mapper/*.xml
(四)后端各层代码的搭建和测试
- 项目结构
2.实体类
package com.example.ajax.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private Integer id;
private String name;
private String msg;
}
- 实体类的接口
package com.example.ajax.mapper;
import com.example.ajax.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
User getUserById(Integer id);
String getMsgById(Integer id);
List<User> getAllUser();
}
- 对接口进行测试
package com.example.ajax;
import com.example.ajax.mapper.UserMapper;
import com.example.ajax.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.*;
@SpringBootTest
public class TestUserMapper {
@Autowired
UserMapper userMapper;
@Test
public void selectById(){
User user=userMapper.getUserById(1);
System.out.println(user);
}
@Test
public void gatAll(){
List< User> users=userMapper.getAllUser();
System.out.println(users);
}
@Test
public void getMag(){
String msg=userMapper.getMsgById(1);
System.out.println(msg);
}
}
- 测试完成后写Service层
(1)Service接口
package com.example.ajax.service;
import com.example.ajax.pojo.User;
import java.util.List;
public interface UserService {
User getUserById(Integer id);
String getMsgById(Integer id);
List<User> getAllUser();
}
(2)Service实现类
package com.example.ajax.service.Impl;
import com.example.ajax.mapper.UserMapper;
import com.example.ajax.pojo.User;
import com.example.ajax.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public User getUserById(Integer id) {
return userMapper.getUserById(id);
}
@Override
public String getMsgById(Integer id) {
return userMapper.getMsgById(id);
}
@Override
public List<User> getAllUser() {
return userMapper.getAllUser();
}
}
- 控制层
package com.example.ajax.controller;
import com.example.ajax.pojo.User;
import com.example.ajax.service.UserService;
import com.google.gson.Gson;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.*;
@Controller
@ResponseBody
@RequestMapping("/msg")
public class UserController {
@Autowired
UserService userService;
@GetMapping("/getJsonOne")
public String getUserById(@Param("id") Integer id){
User user=userService.getUserById(id);
Gson gson = new Gson();
return gson.toJson(user);
}
@GetMapping("/getOne")
public User getUser(@Param("id") Integer id){
User user=userService.getUserById(id);
return user;
}
@GetMapping("/getJsonAll")
public String getUser(){
List<User> users=userService.getAllUser();
Gson gson = new Gson();
return gson.toJson(users);
}
}
(五)前端页面和Ajax数据的测试
- springBoot项目可以直接访问static下的html,所以直接把html放在static下就可以了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery.js"></script>
<script>
$(document).ready(function () {
$('#btn1').click(function () {
showAll();
})
$('#btn2').click(function () {
showOne();
})
})
function showAll(){
console.log("hhhhh")
// (不带参数)向后端请求getJson的方法,返回json数据
$.ajax({
//!----------!点击了按钮1时候,触发showAll函数,这里ajax会的请求地址(url:'/msg/getJsonAll'),请求类型(type:'get),数据类型(dataType:'json')
url:'/msg/getJsonAll',
type:'get',
dataType:'json',
// 成功返回json数据后执行下面的函数:(对数据进行处理显示在页面上)
success:function (data) {
console.log(data)
$('#tabletest').find('tr').remove();
// tds=' <td>id</td>' +
// ' <td>name</td>' +
// ' <td>msg</td>';
// $('#tabletest').append('<tr>'+tds+'</td>');
for(i in data){
var tds;
tds= tds='<td>'+data[i].id+'</td>' +
'<td>'+data[i].name+'</td>'+
'<td>'+data[i].msg+'</td>';
$('#tabletest').append('<tr>'+tds+'</tr>');
}
console.log("11111")
}
})
}
function showOne(){
console.log("oneone")
$.ajax({
url:'/msg/getJsonOne',
type:'get',
dataType:'json',
// 传递的参数
//url拼接参数后就是:
//'/msg/getJsonOne?id=xxx'
data:{"id":$('#id').val()},
// 成功后,后端返回json对象data
success:function (data) {
console.log("success");
console.log(data);
if(data!=null){
$('#tabletest').find('tr').remove();
var tds;
tds= tds='<td>'+data.id+'</td>' +
'<td>'+data.name+'</td>'+
'<td>'+data.msg+'</td>';
$('#tabletest').append('<tr>'+tds+'</tr>');
console.log("查询数据");
}
else{
console.log("查询不到数据");
}
}
});}
</script>
</head>
<body>
<div class="center">
<p id="text"></p>
<button id="btn1">显示所有数据</button>
<input type="text" name="id" id="id" placeholder="请输入id值" >
<button id="btn2">查询</button>
<table id="tabletest">
</table>
</div>
</body>
</html>
(六)结果
- 点击按钮1
- 点击按钮2
就这样~ 简单,可复用来测试关键的代码和逻辑 ~~