关键技术:
前端:Vue+Element+JQuery
后端:Springboot+Springdatajpa
项目流程:
Part I:后端代码
1.创建项目
选择Spring Initializr,JDK选择1.8版本。
导入三个包:Spring Web——spring框架的核心类;Spring Data JPA——整合数据库操作;MYSQL Driver——数据库驱动
Maven使用默认Maven 3。
2..demo框架
SpringBoot 项目一般外层只有两个文件,pom.xml文件 和src文件夹。
pom.xml文件的内容是Spring的一些依赖配置;
src文件夹的内容包括项目的大致结构,src文件夹里面包含main文件夹,main文件夹是java和resource文件夹。其中java里保存的spring后台的框架,resource中有static文件夹是存放静态页面的地方,application.yml用于连接数据库。
注意:启动类应放在与其他层相同的层级上。
Spring框架主要包括四层:
controller:控制层,控制业务逻辑
service:业务层,控制业务
dao:持久层,主要用于数据库交互
entity:实体层,数组库在项目中的类
另外,common包含一个通用配置文件夹里面包含Result(一个返回json数据的包装类)和WebMvcConfig(用于配置跨域访问)的配置类。
pom文件如下:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--添加Springmvc依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springBoot JPA的起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.7.10</version>
<scope>test</scope>
</dependency>
<!-- 打war包时加入此项, 告诉spring-boot tomcat相关jar包用外部的,不要打进去 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope><!--由JDK或者容器提供-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
</project>
3.创建数据库
SQL语句:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`sex` varchar(1) DEFAULT NULL COMMENT '性别',
`address` varchar(255) DEFAULT NULL COMMENT '地址',
`phone` varchar(20) DEFAULT NULL COMMENT '电话',
`create_time` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('2', '张三', '22', '男', '上海市', '13867675656', '2020-12-26');
INSERT INTO `user` VALUES ('3', '李四', '20', '男', '合肥市', '13978786565', '2020-11-18');
INSERT INTO `user` VALUES ('5', '赵柳', '20', '男', '南京市', '13978786565', '2020-11-18');
INSERT INTO `user` VALUES ('6', '钱望', '22', '男', '深圳市', '13867675656', '2020-11-18');
INSERT INTO `user` VALUES ('7', '李云', '20', '男', '合肥市', '13978786565', '2020-11-18');
INSERT INTO `user` VALUES ('8', '张傅', '22', '男', '上海市', '13867675656', '2020-11-18');
INSERT INTO `user` VALUES ('9', '李青', '20', '男', '合肥市', '13978786565', '2020-11-18');
INSERT INTO `user` VALUES ('10', '王二发', '22', '男', '昆明市', '13867675656', '2020-11-18');
INSERT INTO `user` VALUES ('12', '王得贵', '22', '男', '成都市', '13867674565', '2020-11-18');
新建成功:
4.增删改查功能实现
一般按照倒序方式创建项目
(1)首先创建一个与数据库中的表格对应的entity实体类,每一个字段与数据库表字段应对。同时添加getter、setter方法。
@Entity //标注为实体类
@Table(name = "user") //映射数据库user表
public class User {
@Id //设置主键为id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
private String sex;
private String address;
private String phone;
@Column(name = "create_time") //数据库采用驼峰式的结构,添加注释与该实体类createTime字段进行映射
private String createTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
}
(2)配置到dao(mapper)接口,完成数据库多的交互。由于该层需要连接数据库,请确保数据库配置连接成功。
application.yml配置如下:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: 数据库(一般为root)
password: 密码
url: jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2b8
//在该接口中,增删改查的方法不用自己定义
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
//继承JpaRepository,两个泛型参数分别是数据库表和主键类型
}
(3)Service类实现
在Spring data JPA中集成了很多操作数据库的方法,我们可以直接拿来使用。
先创建一个Service类,给一个Service注解,然后注入UserRepository数据库接口,并实现增删改查功能。
@Service
public class UserService {
@Resource
private UserRepository userRepository; //注入数据库接口
//新增与修改功能
//add与update都调用save方法,区别在于add在传递参数时不传id,而update传递id
public void save(User user) {
String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
user.setCreateTime(now);
userRepository.save(user);
}
//删除操作
public void delete(Long id) {
userRepository.deleteById(id);
}
//根据id查询操作,查询失败返回null
public User findById(Long id) {
return userRepository.findById(id).orElse(null);
}
//查找全部
public List<User> findAll() {
return userRepository.findAll();
}
//分页查询
public Page<User> findPage(Integer pageNum, Integer pageSize, String name) {
// 构建分页查询条件,根据create_time倒序排序
Sort sort = Sort.by(Sort.Direction.DESC, "create_time");
//分页查询操作
Pageable pageRequest = PageRequest.of(pageNum - 1, pageSize, sort);
return userRepository.findByNameLike(name, pageRequest);
}
}
自定义模糊查询:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
//继承JpaRepository,两个泛型参数分别是数据库表和主键类型
@Query(value = "select * from user where name like %?1%", nativeQuery = true)
Page<User> findByNameLike(String name, Pageable pageRequest);
}
//项目为前后端分离,前端返回的数据是json格式,标记注解RestController表示返回的数据都是json格式
@RestController
@RequestMapping("/user") //url路径
@ComponentScan("com.example.demo4.controller") //扫描
public class UserController {
@Resource //注入UserService,使用UserService中的方法等
private UserService userService;
// 新增用户
@PostMapping
public Result add(@RequestBody User user) {
userService.save(user);
return Result.success();
}
// 修改用户
@PutMapping
public Result update(@RequestBody User user) {
userService.save(user);
return Result.success();
}
// 删除用户
//delete域名映射将域名映射为id,通过PathVariable接收参数id,根据id删除用户
//Restful用法
@DeleteMapping("/{id}")
public void delete(@PathVariable("id") Long id) {
userService.delete(id);
}
// 根据id查询用户
@GetMapping("/{id}")
public Result<User> findById(@PathVariable Long id) {
return Result.success(userService.findById(id));
}
// 查询所有用户
@GetMapping
public Result<List<User>> findAll() {
return Result.success(userService.findAll());
}
// 分页查询用户
//RequestParam传递两个参数
@GetMapping("/page")
public Result<Page<User>> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize,
@RequestParam(required = false) String name) {
return Result.success(userService.findPage(pageNum, pageSize, name));
}
}
至此,后端代码完成。
Part II:前端代码
前端架构
中间由于从其他地方拷贝过来的代码,以下几个文件被加上了路径导致前端404和没能把element组件渲染,后面修改成以下成功运行,算是一点粗心了。
前端页面代码在index.html完成,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
<!-- 引入样式 -->
<link rel="stylesheet" href="element.css">
</head>
<body>
<div id="app" style="width: 80%; margin: 0 auto">
<h2>用户信息表</h2>
<el-row>
<el-col :span="6" style="margin-bottom: 10px">
<el-button type="primary" @click="add">新增</el-button>
<el-input v-model="name" style="width: 70%" @keyup.enter.native="loadTable(1)"></el-input>
</el-col>
</el-row>
<el-table
:data="page.content"
stripe
border
style="width: 100%">
<el-table-column
prop="name"
label="用户名"
>
</el-table-column>
<el-table-column
prop="age"
label="年龄"
width="180">
</el-table-column>
<el-table-column
prop="sex"
label="性别">
</el-table-column>
<el-table-column
prop="address"
label="地址">
</el-table-column>
<el-table-column
prop="phone"
label="电话">
</el-table-column>
<el-table-column
fixed="right"
label="操作"
width="100">
<template slot-scope="scope">
<el-button type="primary" icon="el-icon-edit" size="small" circle @click="edit(scope.row)"></el-button>
<el-button type="danger" icon="el-icon-delete" size="small" circle @click="del(scope.row.id)"></el-button>
</template>
</el-table-column>
</el-table>
<el-row type="flex" justify="center" style="margin-top: 10px">
<el-pagination
layout="prev, pager, next"
:page-size="pageSize"
:current-page="pageNum"
@prev-click="loadTable"
@current-change="loadTable"
@next-click="loadTable"
:total="page.totalElements">
</el-pagination>
</el-row>
<el-dialog
title="用户信息"
:visible.sync="dialogVisible"
width="30%">
<el-form ref="form" :model="form" label-width="80px">
<el-form-item label="用户名">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="年龄">
<el-input v-model="form.age"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-radio v-model="form.sex" label="男">男</el-radio>
<el-radio v-model="form.sex" label="女">女</el-radio>
</el-form-item>
<el-form-item label="地址">
<el-input v-model="form.address"></el-input>
</el-form-item>
<el-form-item label="电话">
<el-input v-model="form.phone"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</span>
</el-dialog>
</div>
<script src="jquery.min.js"></script>
<script src="vue.js"></script>
<!-- 引入组件库 -->
<script src="element.js"></script>
<script>
new Vue({
el: '#app',
data: {
page: {},
name: '',
pageNum: 1,
pageSize: 8,
dialogVisible: false,
form: {}
},
created() {
this.loadTable(this.pageNum);
},
methods: {
loadTable(num) {
this.pageNum = num;
$.get("/user/page?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize + "&name=" + this.name).then(res => {
this.page = res.data;
});
},
add() {
this.dialogVisible = true;
this.form = {};
},
edit(row) {
this.form = row;
this.dialogVisible = true;
},
save() {
let data = JSON.stringify(this.form);
if (this.form.id) {
// 编辑
$.ajax({
url: '/user',
type: 'put',
contentType: 'application/json',
data: data
}).then(res => {
this.dialogVisible = false;
this.loadTable(1);
})
} else {
// 新增
$.ajax({
url: '/user',
type: 'post',
contentType: 'application/json',
data: data
}).then(res => {
this.dialogVisible = false;
this.loadTable(1);
})
}
},
del(id) {
$.ajax({
url: '/user/' + id,
type: 'delete',
contentType: 'application/json'
}).then(res => {
this.loadTable(1);
})
}
}
})
</script>
</body>
</html>
** 项目展示:**
版权归原作者 Tender Surrender 所有, 如有侵权,请联系我们删除。