目录
一、搭建环境
①数据库
②使用HBuilderX搭建前端环境
③使用idea搭建后台环境
二、编写所需的接口
BookController
BookMapper
BookService
BookServiceImpl
BookMapper.xml
三、写前端
action.js
BookList.vue
一、搭建环境
①数据库
运行SQL文件,或者创建项目中所要用到的数据库
②使用HBuilderX搭建前端环境
将准备好的前端的spa项目导入该工具,然后下载所需要node.js
测试一下能否看见版本
若命令无效 则用管理员的身份打开黑窗口 进入对应的位置再运行,命令有效就下载所需的文件 npm i
下载完成之后 运行就能看见以下的页面
③使用idea搭建后台环境
将准备好的没有写接口的后台导入idea
一定要修改maven的地址 还有以下的一些配置
pom.xml
<?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.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zking</groupId>
<artifactId>spboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spboot</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<mysql.version>5.1.44</mysql.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<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>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!--pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<!--freemarker-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
<configuration>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bookshop?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
generatorConfig.xml
生成代码的类 修改jar的位置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!-- 引入配置文件 -->
<properties resource="jdbc.properties"/>
<!--指定数据库jdbc驱动jar包的位置-->
<classPathEntry location="D:\maven\repository\mysql\mysql-connector-java\8.0.29\mysql-connector-java-8.0.29.jar\"/>
<!-- 一个数据库一个context -->
<context id="infoGuardian">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 01 指定javaBean生成的位置 -->
<!-- targetPackage:指定生成的model生成所在的包名 -->
<!-- targetProject:指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="com.zking.spboot.model"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<property name="trimStrings" value="false"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!-- 02 指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.zking.spboot.mapper"
targetProject="src/main/resources">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 03 生成XxxMapper接口 -->
<!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
<!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
<!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="com.zking.spboot.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 配置表信息 -->
<!-- schema即为数据库名 -->
<!-- tableName为对应的数据库表 -->
<!-- domainObjectName是要生成的实体类 -->
<!-- enable*ByExample是否生成 example类 -->
<!--<table schema="" tableName="t_book" domainObjectName="Book"-->
<!--enableCountByExample="false" enableDeleteByExample="false"-->
<!--enableSelectByExample="false" enableUpdateByExample="false">-->
<!--<!– 忽略列,不生成bean 字段 –>-->
<!--<!– <ignoreColumn column="FRED" /> –>-->
<!--<!– 指定列的java数据类型 –>-->
<!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>-->
<!--</table>-->
<table schema="" tableName="t_book" domainObjectName="Book"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
<!-- 忽略列,不生成bean 字段 -->
<!-- <ignoreColumn column="FRED" /> -->
<!-- 指定列的java数据类型 -->
<!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> -->
</table>
</context>
</generatorConfiguration>
application.yml
server:
port: 8080
servlet:
context-path: /spboot
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/bookshop?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: true
test-on-return: false
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
login-username: admin
login-password: admin
allow: 127.0.0.1
#deny: 192.168.1.100
freemarker:
cache: false
charset: UTF-8
content-type: text/html
suffix: .ftl
template-loader-path: classpath:/templates
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.zking.spboot.model
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.zking.spboot.mapper: debug
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
启动项目
二、编写所需的接口
BookController
package com.zking.spboot.controller;
import com.zking.spboot.model.Book;
import com.zking.spboot.service.BookService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author cdl
* @site www.cdl.com
* @create 2022-11-17 20:37
*/
@RestController
@RequestMapping("/book")
public class BookController {
@Autowired
private BookService bookService;
//带模糊查询的查询所有的接口
@RequestMapping("/query")
public JsonResponseBody<?> query(Book book){
List<Book> books = bookService.query(book);
return new JsonResponseBody<>(200,"ok",books);
}
@RequestMapping("/add")
public JsonResponseBody<?> add(Book book){
bookService.insert(book);
return new JsonResponseBody<>();
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class JsonResponseBody<T>{
private int code =200;
private String msg ="ok";
private T data;
}
}
BookMapper
package com.zking.spboot.mapper;
import com.zking.spboot.model.Book;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface BookMapper {
int deleteByPrimaryKey(Integer id);
/**
* 新增
* @param record
* @return
*/
int insert(Book record);
/**
* *带模糊查询的查询所有
* @param book
* @return
*/
List<Book> query(Book book);
int insertSelective(Book record);
Book selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Book record);
int updateByPrimaryKey(Book record);
}
BookService
package com.zking.spboot.service;
import com.zking.spboot.model.Book;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.util.List;
public interface BookService {
/**
* 新增
* @param record
* @return
*/
int insert(Book record);
/**
* *带模糊查询的查询所有
* @param book
* @return
*/
List<Book> query(Book book);
}
BookServiceImpl
package com.zking.spboot.service.impl;
import com.zking.spboot.mapper.BookMapper;
import com.zking.spboot.model.Book;
import com.zking.spboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author cdl
* @site www.cdl.com
* @create 2022-11-17 20:35
*/
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public int insert(Book record) {
return bookMapper.insert(record);
}
@Override
public List<Book> query(Book book) {
return bookMapper.query(book);
}
}
BookMapper.xml
添加一个带模糊查询的方法
<select id="query" resultType="com.zking.spboot.model.Book">
select <include refid="Base_Column_List" /> from t_book where 1=1
<if test="null!=bookname and ''!=bookname">
and bookname like concat('%',#{bookname},'%')
</if>
</select>
因为id是自增的,将id的值删除
运行项目访问能拿到所有的值
三、写前端
action.js
/**
* 对后台请求的地址的封装,URL格式如下:
* 模块名_实体名_操作
*/
export default {
//服务器
'SERVER': 'http://localhost:8080/spboot',
'All':'/book/query',
'ADD':'/book/add',
//获得请求的完整地址,用于mockjs测试时使用
'getFullPath': k => {
return this.SERVER + this[k];
}
}
router中index.js
import Vue from 'vue'
import Router from 'vue-router'
import BookList from '@/views/BookList'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'BookList',
component: BookList
}
]
})
BookList.vue
<template>
<div>
<h1 align="center">SpringBoot阶段机试,ts={{ts}}</h1>
<!--搜索栏 -->
<el-form :inline="true">
<el-form-item label="书本名称">
<el-input v-model="bookname"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="query">查询</el-button>
<el-button type="primary" @click="open">新增</el-button>
</el-form-item>
</el-form>
<!-- 数据表格 -->
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="id" label="编号" width="180">
</el-table-column>
<el-table-column prop="bookname" label="名称" width="180">
</el-table-column>
<el-table-column prop="price" label="价格">
</el-table-column>
<el-table-column prop="booktype" label="类型">
</el-table-column>
</el-table>
<!-- 弹出框(新增) -->
<el-dialog @close="close" title="书本新增" :visible.sync="dialogFormVisible">
<el-form :model="book" :rules="rules" ref="book">
<el-form-item prop="bookname" label="书本名称" :label-width="formLabelWidth">
<el-input v-model="book.bookname" autocomplete="off"></el-input>
</el-form-item>
<el-form-item prop="price" label="书本价格" :label-width="formLabelWidth">
<el-input v-model="book.price" autocomplete="off"></el-input>
</el-form-item>
<el-form-item prop="booktype" label="书本类型" :label-width="formLabelWidth">
<el-select v-model="book.booktype" placeholder="请选择书本类型">
<el-option label="散文" value="散文"></el-option>
<el-option label="诗歌" value="诗歌"></el-option>
</el-select>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
data: function() {
return {
ts: new Date().getTime(),
bookname: '',
tableData: [],
dialogFormVisible: false,
formLabelWidth: '100px',
book: {
bookname: '',
price: '',
booktype: ''
},
rules: {
bookname: [{
required: true,
message: '请输入书本名称',
trigger: 'blur'
}],
price: [{
required: true,
message: '请输入书本价格',
trigger: 'blur'
}],
booktype: [{
required: true,
message: '请选择书本类型',
trigger: 'change'
}],
}
};
},
methods: {
close:function(){
this.$refs['book'].resetFields();
},
save: function() {
this.$refs['book'].validate((valid) => {
if (valid) {
let url = this.axios.urls.ADD;
this.axios.post(url, this.book).then(resp => {
let rs = resp.data;
if(rs.code==200){
//关闭对话框
this.dialogFormVisible=false;
//刷新列表
this.query();
}else{
}
}).catch(err => {
});
} else {
console.log('error submit!!');
return false;
}
});
},
open: function() {
this.dialogFormVisible = true;
},
query: function() {
//查询参数
let params = {
bookname: this.bookname
}
//请求路径
let url = this.axios.urls.All;
//发起Ajax请求
this.axios.post(url, params).then(resp => {
let rs = resp.data;
this.tableData = rs.data;
}).catch(err => {
});
}
}
}
</script>
<style>
</style>
运行结果: