文章目录
一、环境需求
jdk 1.8
mysql 5.7
node
navicat
idea
浏览器Json插件:jsonview
-安装插件
1.vue
官网:https://cn.vuejs.org/v2/guide/
方式 一
方式同:https://blog.csdn.net/weixin_44953928/article/details/124458528
方式 二
2.element-ul
官网:https://element.eleme.cn/#/zh-CN
- 测试是否成功
2 vue 的简单介绍
2.0 vue的快速启动设置
2.1 组件:简单介绍
组件的3部分
2.2全局布置
2.3 组件内设置和改动
style="min-height: 100vh"
//height这个标签的高度, line-height:属性用于设置多行元素的空间量,如多行文本的间距。text-align:用来设置元素中的的文本对齐方式
style="height: 60px; line-height: 60px; text-align: center"
//背景颜色
background-color="rgb(48,65,86)"
//文字颜色
text-color="#fff"
// 点击高亮
active-text-color="#ffd04b"
//鼠标手型,cursor(鼠标手型)属性
style="cursor: pointer"
//点击收缩(进行了绑定)
:collapse-transition="false"
:collapse="isCollapse"
2.3.1 style
- 问题
vh就是当前屏幕可见高度的1%,也就是说,height:100vh == height:100%;
但是有个好处是当元素没有内容时候,设置height:100%该元素不会被撑开,
但是设置height:100vh,该元素会被撑开屏幕高度一致。
2.3.2背景颜色和文字颜色
//背景色
background-color="rgb(48,65,86)"
//文字颜色
text-color="#fff"
2.3.3 点击高亮
2.3.4 导航栏收缩
2.3.5 加图片
2.3.3 主页设置(搜索框、分页等等)
分页,表格添加
3.后端
3.1创建sprootboot
如果本地没有配置Maven,则采用pom里配置阿里云仓库,(这里我配置了本地的maven,所以这里忽略)
<repositories>
<repository>
<id>nexus-aliyun</id>
<name>nexus-aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
3.2 配置application.properties或者application.yaml 或者application.yml
- application.yml
#重新设置端口
server:
port: 9000
# mysql
spring:
datasource:
#MySQL配置
driverClassName: com.mysql.cj.jdbc.Driver
#serverTimezone=GMT%2b8 东八区
url: jdbc:mysql://localhost:3306/tests?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&serverTimezone=GMT%2b8
username: root
password: 123456
3.3 navicat创建新的数据库
3.4 做测试
- 使用控制层
3.6几大类的创建(entity、mapper)
3.6.1 创建entity(实体类)
方式一
方式二(lombok:不建议使用)
@Getter //为字段创建getter方法
@Setter //为字段创建setter
@EqualsAndHashCode //实现equals()和hashCode()
@ToString //实现toString()
@Data //使用上面四个注解的特征
@Cleanup //关闭流
@Synchronized //对象上同步
@SneakyThrows //抛出异常
@NoArgsConstructor //注解在类上;为类提供一个无参的构造方法
@AllArgsConstructor //注解在类上;为类提供一个全参的构造方法
@Data //注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法
@Setter //可用在类或属性上;为属性提供 setting 方法
@Getter //可用在类或属性上;为属性提供 getting 方法
3.6.2 mapper (dao)接口
3.6.3 Controller 控制层测试
3.7进一步测试(增加数据和更新)
3.7.1 mapper和controller :只增加
- mapper
@Mapper
@RestController
public interface UserMapper {
@Select("SELECT * from sys_user")
List<User> findAll();
// @Insert("INSERT into sys_user(username,password,password,email,phone,address)VALUES(#{username},#{password},#{password},#{email},#{phone},#{address})")
// int insert(User user);
@Insert("INSERT into sys_user(username, password,nickname,email,phone,address) VALUES (#{username}, #{password}," +
" #{nickname}, #{email},#{phone}, #{address})")
int insert(User user);
}
- controller
//@RestController加在类上面的注解,使得类里面的每个方法都将json/xml返回数据加返回到前台页面中。
@RestController
//代表统一的给这个类加一个前缀
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
// 新增
//@RequestBody:把前台传过来的JSON对象转换成Java对象
@PostMapping
public Integer save(@RequestBody User user){
return userMapper.insert(user);
}
//这是get请求
@GetMapping("/")
public List<User> index() {
List<User> all = userMapper.findAll();
return all;
}
}
3.7.2 使用post测试
postman下载
https://app.getpostman.com/app/download/win64
postman测试接口
3.7.3 mapper、service、controller :(增加和更新)
mapper
@Mapper
@RestController
public interface UserMapper {
@Select("SELECT * from sys_user")
List<User> findAll();
//添加
@Insert("INSERT into sys_user(username, password,nickname,email,phone,address) VALUES (#{username}, #{password}," +
" #{nickname}, #{email},#{phone}, #{address})")
int insert(User user);
//更新
@Update("update sys_user set username =#{username},password=#{password},nickname=#{nickname}, email=#{email},phone=#{phone},address=#{address} where id=#{id}")
int update(User user);
}
service
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public int save(User user) {
if (user.getId() == null) { // user没有id,则表示是新增
return userMapper.insert(user);
} else { // 否则为更新
return userMapper.update(user);
}
}
}
controller
//@RestController加在类上面的注解,使得类里面的每个方法都将json/xml返回数据加返回到前台页面中。
@RestController
//代表统一的给这个类加一个前缀
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@Autowired
private UserService userService;
// 新增和更新
//@RequestBody:把前台传过来的JSON对象转换成Java对象
@PostMapping
public Integer save(@RequestBody User user){
return userService.save(user);
}
//这是get请求
@GetMapping("/")
public List<User> index() {
List<User> all = userMapper.findAll();
return all;
}
}
3.8 使用mybatis(增删改查的实现)
3.8.1创建在resources下的user.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=对应dao(mapper)的路径-->
<mapper namespace="com.xiao.mapper.UserMapper">
<!-- resultType是entity文件夹下ueser的对象-->
<select id="getUserByMassage" resultType="com.xiao.entity.User">
</select>
<update id="update">
update sys_user
<set>
<if test="username != null">
username = #{username},
</if>
<!-- if test="password != null">-->
<!-- password = #{password}-->
<!-- </if>-->
<if test="nickname != null">
nickname = #{nickname},
</if>
<if test="email != null">
email = #{email},
</if>
<if test="phone != null">
phone = #{phone},
</if>
<if test="address != null">
address = #{address}
</if>
</set>
<where>
id = #{id}
</where>
</update>
</mapper>
3.8.2 UserController.java
//@RestController加在类上面的注解,使得类里面的每个方法都将json/xml返回数据加返回到前台页面中。
@RestController
//代表统一的给这个类加一个前缀
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@Autowired
private UserService userService;
// 新增和更新
//@RequestBody:把前台传过来的JSON对象转换成Java对象
@PostMapping
public Integer save(@RequestBody User user){
return userService.save(user);
}
//这是get请求,查询所有数据
@GetMapping("/")
public List<User> index() {
List<User> all = userMapper.findAll();
return all;
}
//删除
// @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过
@DeleteMapping("/{id}")
public Integer delete(@PathVariable Integer id) {
return userMapper.deleteById(id);
}
}
3.8.3 UserMapper.java
@Mapper
@RestController
public interface UserMapper {
@Select("SELECT * from sys_user")
List<User> findAll();
//添加
@Insert("INSERT into sys_user(username, password,nickname,email,phone,address) VALUES (#{username}, #{password}," +
" #{nickname}, #{email},#{phone}, #{address})")
int insert(User user);
//更新
//@Update("update sys_user set username =#{username},password=#{password},nickname=#{nickname}, email=#{email},phone=#{phone},address=#{address} where id=#{id}")
int update(User user);
@Delete("delete from sys_user where id = #{id}")
Integer deleteById(@Param("id") Integer id);
}
3.8.4 UserService.java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public int save(User user) {
if (user.getId() == null) { // user没有id,则表示是新增
return userMapper.insert(user);
} else { // 否则为更新
return userMapper.update(user);
}
}
}
3.8.5 application.yml
#重新设置端口
server:
port: 9000
# mysql
spring:
datasource:
#MySQL配置
driverClassName: com.mysql.cj.jdbc.Driver
#serverTimezone=GMT%2b8 东八区
url: jdbc:mysql://localhost:3306/tests?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&serverTimezone=GMT%2b8
username: root
password: 123456
mybatis:
mapper-locations: mapper/*.xml #扫描所有的mybatis的mapper文件的xml文件
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #这是个日志
4.解决一些常见问题
4.1 跨域问题
-
方式一 :就只在controller里加一个@CrossOrigin(“*”)就可以了
-
方式二
import org.springframework.web.filter.CorsFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
public class CorsConfig {
// 当前跨域请求最大有效时长。这里默认1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 ,方法"POST", "GET", "PUT", "OPTIONS", "DELETE"
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
4.2 忽略某个字段,不展示给前端
@JsonIgnore
5.结合前后端结合
5.1 实现分页
5.1.0 首先解决跨域问题
5.1.1 实现分页后端
分页思路
SELECT * from sys_user limit 0,2; --第一页
– (2 -1) * 2 = 2
SELECT * from sys_user limit 2,2; --第二页
– (3-1)* 2 = 4
SELECT * from sys_user limit 4,2; --第三页
– 结论: limit第一个参数 = (pageNum - 1) * pageSize
- mapper
@Mapper
@RestController
public interface UserMapper {
@Select("SELECT * from sys_user")
List<User> findAll();
//添加
@Insert("INSERT into sys_user(username, password,nickname,email,phone,address) VALUES (#{username}, #{password}," +
" #{nickname}, #{email},#{phone}, #{address})")
int insert(User user);
//更新
//@Update("update sys_user set username =#{username},password=#{password},nickname=#{nickname}, email=#{email},phone=#{phone},address=#{address} where id=#{id}")
int update(User user);
@Delete("delete from sys_user where id = #{id}")
Integer deleteById(@Param("id") Integer id);
//分页处理
@Select("select * from sys_user limit #{pageNum}, #{pageSize}")
List<User> selectPage(Integer pageNum, Integer pageSize);
//总页数
@Select("select count(*) from sys_user")
Integer selectTotal();
}
- UserController
//@RestController加在类上面的注解,使得类里面的每个方法都将json/xml返回数据加返回到前台页面中。
@RestController
//代表统一的给这个类加一个前缀
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@Autowired
private UserService userService;
// 新增和更新
//@RequestBody:把前台传过来的JSON对象转换成Java对象
@PostMapping
public Integer save(@RequestBody User user){
return userService.save(user);
}
//这是get请求,查询所有数据
@GetMapping("/")
public List<User> findAll() {
List<User> all = userMapper.findAll();
return all;
}
//删除
// @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过
@DeleteMapping("/{id}")
public Integer delete(@PathVariable Integer id) {
return userMapper.deleteById(id);
}
// 分页查询
// 接口路径:/user/page?pageNum=1&pageSize=10
// @RequestParam接受
// limit第一个参数 = (pageNum - 1) * pageSize
// pageSize
@GetMapping("/page")
public Map<String, Object> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
pageNum = (pageNum - 1) * pageSize;
List<User> data = userMapper.selectPage( pageNum, pageSize);
Integer total = userMapper.selectTotal();
Map<String, Object> res = new HashMap<>();
res.put("data", data);
res.put("total", total);
return res;
}
}
5.1.2 实现分页前端
5.2 实现查询
5.2.1 先只实现一个查询
后端
前端
6.mybatis-plus的使用
官网:https://baomidou.com/
- mybatis-plus依赖
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
6.1 mybatis-plus分页插件的使用(contrller、entity、mapper、service都跟着改)
- application.yml
#重新设置端口
server:
port: 9000
# mysql
spring:
datasource:
#MySQL配置
driverClassName: com.mysql.cj.jdbc.Driver
#serverTimezone=GMT%2b8 东八区
url: jdbc:mysql://localhost:3306/tests?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&serverTimezone=GMT%2b8
username: root
password: 123456
mybatis:
mapper-locations: mapper/*.xml #扫描所有的mybatis的mapper文件的xml文件
# configuration:
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #这是个日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #这是个日志
- 添加分页插件
6.2 集成Swagger-Ui
访问地址:http://localhost:9000/swagger-ui/index.html
pop.xml
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
SwaggerConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableOpenApi
public class SwaggerConfig {
/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
*
* @return
*/
@Bean
public Docket restApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("标准接口")
.apiInfo(apiInfo("Spring Boot中使用Swagger2构建RESTful APIs", "1.0"))
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.qingge.springboot.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://ip:port/swagger-ui.html
*
* @return
*/
private ApiInfo apiInfo(String title, String version) {
return new ApiInfoBuilder()
.title(title)
.description("更多请关注: https://blog.csdn.net/xqnode")
.termsOfServiceUrl("https://blog.csdn.net/xqnode")
.contact(new Contact("xqnode", "https://blog.csdn.net/xqnode", "xiaqingweb@163.com"))
.version(version)
.build();
}
}
6.3 实现分页
- UserController.java
package com.xiao.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiao.entity.User;
import com.xiao.mapper.UserMapper;
import com.xiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//@RestController加在类上面的注解,使得类里面的每个方法都将json/xml返回数据加返回到前台页面中。
@RestController
@CrossOrigin("*")
//代表统一的给这个类加一个前缀
@RequestMapping("/user")
public class UserController {
// @Autowired
// private UserMapper userMapper;
@Autowired
private UserService userService;
// // 新增和更新
// //@RequestBody:把前台传过来的JSON对象转换成Java对象
// @PostMapping
// public Integer save(@RequestBody User user){
// return userService.save(user);
// }
// 新增和修改
@PostMapping
public boolean save(@RequestBody User user) {
// 新增或者更新
return userService.saveUser(user);
}
//这是get请求,
// 查询所有数据
@GetMapping("/")
public List<User> findAll() {
// List<User> all = userMapper.findAll();
// return all;
return userService.list();
}
//删除
// @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过
// @DeleteMapping("/{id}")
// public Integer delete(@PathVariable Integer id) {
// return userMapper.deleteById(id);
// }
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
return userService.removeById(id);
}
// 分页查询
// 接口路径:/user/page?pageNum=1&pageSize=10
// @RequestParam接受
// limit第一个参数 = (pageNum - 1) * pageSize
// pageSize
// @GetMapping("/page")
// public Map<String, Object> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
// @RequestParam String username) {
// pageNum = (pageNum - 1) * pageSize;
// List<User> data = userMapper.selectPage( pageNum, pageSize, username);
// Integer total = userMapper.selectTotal(username);
// Map<String, Object> res = new HashMap<>();
// res.put("data", data);
// res.put("total", total);
// return res;
// }
// 分页查询 - mybatis-plus的方式
@GetMapping("/page")
public IPage<User> findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String username,
@RequestParam(defaultValue = "") String nickname,
@RequestParam(defaultValue = "") String address) {
IPage<User> page = new Page<>(pageNum, pageSize);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if (!"".equals(username)) {
queryWrapper.like("username", username);
}
if (!"".equals(nickname)) {
queryWrapper.like("nickname", nickname);
}
if (!"".equals(address)) {
queryWrapper.like("address", address);
}
return userService.page(page, queryWrapper);
}
}
7. 前端实现(封装axios)
7.1 vue安装axios 和 request.js封装
npm i axios -S
request.js封装
import axios from 'axios'
const request = axios.create({
baseURL: '/api',
timeout: 5000
})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request
import axios from 'axios'
const request = axios.create({
baseURL: '/api', // 注意!! 这里是全局统一加上了 '/api' 前缀,也就是说所有接口都会加上'/api'前缀在,页面里面写接口的时候就不要加 '/api'了,否则会出现2个'/api',类似 '/api/api/user'这样的报错,切记!!!
timeout: 5000
})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request
7.2 后端加入批量删除
UserController.java
package com.xiao.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiao.entity.User;
import com.xiao.mapper.UserMapper;
import com.xiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//@RestController加在类上面的注解,使得类里面的每个方法都将json/xml返回数据加返回到前台页面中。
@RestController
@CrossOrigin("*")
//代表统一的给这个类加一个前缀
@RequestMapping("/user")
public class UserController {
// @Autowired
// private UserMapper userMapper;
@Autowired
private UserService userService;
// // 新增和更新
// //@RequestBody:把前台传过来的JSON对象转换成Java对象
// @PostMapping
// public Integer save(@RequestBody User user){
// return userService.save(user);
// }
// 新增和修改
@PostMapping
public boolean save(@RequestBody User user) {
// 新增或者更新
return userService.saveUser(user);
}
//这是get请求,
// 查询所有数据
@GetMapping("/")
public List<User> findAll() {
// List<User> all = userMapper.findAll();
// return all;
return userService.list();
}
//删除
// @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过
// @DeleteMapping("/{id}")
// public Integer delete(@PathVariable Integer id) {
// return userMapper.deleteById(id);
// }
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
return userService.removeById(id);
}
//批量删除
@PostMapping("/del/batch")
public boolean deleteBatch(@RequestBody List<Integer> ids) { // [1,2,3]
return userService.removeByIds(ids);
}
// 分页查询
// 接口路径:/user/page?pageNum=1&pageSize=10
// @RequestParam接受
// limit第一个参数 = (pageNum - 1) * pageSize
// pageSize
// @GetMapping("/page")
// public Map<String, Object> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
// @RequestParam String username) {
// pageNum = (pageNum - 1) * pageSize;
// List<User> data = userMapper.selectPage( pageNum, pageSize, username);
// Integer total = userMapper.selectTotal(username);
// Map<String, Object> res = new HashMap<>();
// res.put("data", data);
// res.put("total", total);
// return res;
// }
// 分页查询 - mybatis-plus的方式
@GetMapping("/page")
public IPage<User> findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String username,
@RequestParam(defaultValue = "") String nickname,
@RequestParam(defaultValue = "") String address) {
IPage<User> page = new Page<>(pageNum, pageSize);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if (!"".equals(username)) {
queryWrapper.like("username", username);
}
if (!"".equals(nickname)) {
queryWrapper.like("nickname", nickname);
}
if (!"".equals(address)) {
queryWrapper.like("address", address);
}
// //这是倒叙
// queryWrapper.orderByDesc("id");
return userService.page(page, queryWrapper);
}
}
7.3 前端加入批量删除
<template>
<el-container style="min-height: 100vh">
<el-aside :width="sideWidth + 'px'" style="background-color: rgb(238, 241, 246); box-shadow: 2px 0 6px rgb(0 21 41);">
<el-menu :default-openeds="['1', '3']" style="min-height: 100%; overflow-x: hidden"
background-color="rgb(48, 65, 86)"
text-color="#fff"
active-text-color="#ffd04b"
:collapse-transition="false"
:collapse="isCollapse"
>
<div style="height: 60px; line-height: 60px; text-align: center">
<img src="../assets/logo.png" alt="" style="width: 20px; position: relative; top: 5px; margin-right: 5px">
<b style="color: white" v-show="logoTextShow">后台管理系统</b>
</div>
<el-submenu index="1">
<template slot="title">
<i class="el-icon-message"></i>
<span slot="title">导航一</span>
</template>
<el-menu-item-group>
<template slot="title">分组一</template>
<el-menu-item index="1-1">选项1</el-menu-item>
<el-menu-item index="1-2">选项2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="分组2">
<el-menu-item index="1-3">选项3</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<template slot="title">选项4</template>
<el-menu-item index="1-4-1">选项4-1</el-menu-item>
</el-submenu>
</el-submenu>
<el-submenu index="2">
<template slot="title">
<i class="el-icon-menu"></i>
<span slot="title">导航二</span>
</template>
<el-menu-item-group>
<template slot="title">分组一</template>
<el-menu-item index="2-1">选项1</el-menu-item>
<el-menu-item index="2-2">选项2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="分组2">
<el-menu-item index="2-3">选项3</el-menu-item>
</el-menu-item-group>
<el-submenu index="2-4">
<template slot="title">选项4</template>
<el-menu-item index="2-4-1">选项4-1</el-menu-item>
</el-submenu>
</el-submenu>
<el-submenu index="3">
<template slot="title">
<i class="el-icon-setting"></i>
<span slot="title">导航三</span>
</template>
<el-menu-item-group>
<template slot="title">分组一</template>
<el-menu-item index="3-1">选项1</el-menu-item>
<el-menu-item index="3-2">选项2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="分组2">
<el-menu-item index="3-3">选项3</el-menu-item>
</el-menu-item-group>
<el-submenu index="3-4">
<template slot="title">选项4</template>
<el-menu-item index="3-4-1">选项4-1</el-menu-item>
</el-submenu>
</el-submenu>
</el-menu>
</el-aside>
<el-container>
<el-header style="font-size: 12px; border-bottom: 1px solid #ccc; line-height: 60px; display: flex">
<div style="flex: 1; font-size: 20px">
<span :class="collapseBtnClass" style="cursor: pointer" @click="collapse"></span>
</div>
<el-dropdown style="width: 70px; cursor: pointer">
<span>王小虎</span><i class="el-icon-arrow-down" style="margin-left: 5px"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>个人信息</el-dropdown-item>
<el-dropdown-item>退出</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</el-header>
<el-main>
<div style="margin-bottom: 30px">
<el-breadcrumb separator="/">
<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>用户管理</el-breadcrumb-item>
</el-breadcrumb>
</div>
<!--搜索框-->
<div style="margin: 10px 0">
<el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="username"></el-input>
<el-input style="width: 200px" placeholder="请输入邮箱" suffix-icon="el-icon-message" v-model="email" class="ml-5"></el-input>
<el-input style="width: 200px" placeholder="请输入地址" suffix-icon="el-icon-position" v-model="address" class="ml-5"></el-input>
<el-button class="ml-5" type="primary" @click="load">搜索</el-button>
<el-button type="warning" @click="reset">重置</el-button>
</div>
<!-- 一些按钮 -->
<div style="margin: 10px 0">
<el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
<el-popconfirm
class="ml-5"
confirm-button-text='确定'
cancel-button-text='我再想想'
icon="el-icon-info"
icon-color="red"
title="您确定批量删除这些数据吗?"
@confirm="delBatch"
>
<el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
</el-popconfirm>
<el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
<el-button type="primary">导出 <i class="el-icon-top"></i></el-button>
</div>
<el-table :data="tableData" border stripe :header-cell-class-name="headerBg" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column prop="id" label="ID" width="80"></el-table-column>
<el-table-column prop="username" label="用户名" width="140"></el-table-column>
<el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
<el-table-column prop="email" label="邮箱"></el-table-column>
<el-table-column prop="phone" label="电话"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
<el-table-column label="操作" width="300" align="center">
<template slot-scope="scope">
<el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
<el-popconfirm
class="ml-5"
confirm-button-text='确定'
cancel-button-text='我再想想'
icon="el-icon-info"
icon-color="red"
title="您确定删除吗?"
@confirm="del(scope.row.id)"
>
<el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
<!-- 分页的效果-->
<div style="padding: 10px 0">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pageNum"
:page-sizes="[5, 10, 15, 20]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
<el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="30%" >
<el-form label-width="80px" size="small">
<el-form-item label="用户名">
<el-input v-model="form.username" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="昵称">
<el-input v-model="form.nickname" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="邮箱">
<el-input v-model="form.email" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="电话">
<el-input v-model="form.phone" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="地址">
<el-input v-model="form.address" autocomplete="off"></el-input>
</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>
</el-main>
</el-container>
</el-container>
</template>
<script>
import request from "@/utils/request";
export default {
name: 'Home',
data() {
// const item = {
// date: '2016-05-02',
// name: '王小虎',
// address: '上海市普陀区金沙江路 1518 弄'
// };
return {
//tableData: Array(10).fill(item),
tableData: [],
total:0,
pageNum: 1,
pageSize: 5,
username: "",
email: "",
address: "",
form: {}, //添加表格,修改表格数据
dialogFormVisible: false, // 是否隐藏
multipleSelection: [], //批量删除
msg: "hello 青哥哥",
collapseBtnClass: 'el-icon-s-fold',
isCollapse: false,
sideWidth: 200,
logoTextShow: true,
headerBg: 'headerBg'
}
},
created() {
// 请求分页查询数据
this.load()
},
methods:{
collapse()
{ // 点击收缩按钮触发
this.isCollapse = !this.isCollapse
if (this.isCollapse) { // 收缩
this.sideWidth = 64
this.collapseBtnClass = 'el-icon-s-unfold'
this.logoTextShow = false
} else { // 展开
this.sideWidth = 200
this.collapseBtnClass = 'el-icon-s-fold'
this.logoTextShow = true
}
},
load(){
// request.get("http://localhost:9000/user/page?pageNum="+this.pageNum+"&pageSize=" +this.pageSize+ "&username=" + this.username).then(res => {
// console.log(res)
// this.tableData=res.records
// this.total=res.total
// })
request.get("/user/page",{
params:{
pageNum:this.pageNum,
pageSize:this.pageSize,
username:this.username,
email: this.email,
address:this.address,
}
}).then(res => {
console.log(res)
this.tableData=res.records
this.total=res.total
})
// fetch("http://localhost:9000/user/page?pageNum="+this.pageNum+"&pageSize=" +
// this.pageSize+ "&username=" + this.username).then(res => res.json()).then(res => {
// console.log(res)
// this.tableData=res.data
// this.total=res.total
// })
},
//更新页数和总数
handleSizeChange(pageSize) {
console.log(pageSize)
this.pageSize = pageSize
this.load()
},
handleCurrentChange(pageNum) {
console.log(pageNum)
this.pageNum = pageNum
this.load()
},
//更新
save() {
request.post("/user", this.form).then(res => {
if (res) {
this.$message.success("保存成功")
this.dialogFormVisible = false
this.load()
} else {
this.$message.error("保存失败")
}
})
},
handleAdd() {
this.dialogFormVisible = true
this.form = {}
},
handleEdit(row) {
this.form = row
this.dialogFormVisible = true
},
del(id) {
request.delete("/user/" + id).then(res => {
if (res) {
this.$message.success("删除成功")
this.load()
} else {
this.$message.error("删除失败")
}
})
},
handleSelectionChange(val) {
console.log(val)
this.multipleSelection = val
},
//批量删除
delBatch() {
let ids = this.multipleSelection.map(v => v.id) // [{}, {}, {}] => [1,2,3]
request.post("/user/del/batch", ids).then(res => {
if (res) {
this.$message.success("批量删除成功")
this.load()
} else {
this.$message.error("批量删除失败")
}
})
},
//归零
reset() {
this.username = ""
this.email = ""
this.address = ""
this.load()
},
},
}
</script>
<style>
.headerBg {
background: #eee!important;
}
</style>