(一):创建SpringBoot项目(注意:在创建项目时要导入springboot-web、mysql-driver、等依赖)
(二):pom展示
<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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.2.RELEASEversion>
<relativePath/>
parent>
<groupId>com.hailonggroupId>
<artifactId>admin_vueartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>admin_vuename>
<description>admin_vuedescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.2.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>3.0.0version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocityartifactId>
<version>1.7version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.7.20version>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-ooxmlartifactId>
<version>4.1.2version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
project>
(三):在后端解决跨域
1.创建一个CorsConfig工具类
package com.hailong.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
//配置注解
@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 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
至此后端的跨域配置合适:
vue项目中
(一)安装axios
npm i axios
(二)封装request请求
创建一个utils.request.js
import axios from 'axios'
const request = axios.create({
baseURL: 'http://localhost:9000', // 该地址为后端访问地址
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
(三):使用axios发请求
搜索
新增
批量删除
导入
导出
编辑
删除
(四):创建entity中的实体类user
package com.hailong.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//自动装配get/set
@Data
构造无参方法
//@NoArgsConstructor
构造有参方法
//@AllArgsConstructor
@TableName(value = "sys_user")
public class User {
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String username;
private String password;
private String nickname;
private String email;
private String phone;
private String address;
@TableField(value = "avatar_url")
private String avatar;
}
(五)创建mapper接口方法
package com.hailong.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hailong.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
//@Mapper
public interface UserDao extends BaseMapper<User> {
List<User> findAll();
int insertUser(User user);
int updateUser(User user);
Integer deleteById(@Param("id") Integer id);
// List selectPage(Integer pageNum,Integer pageSize,String username);
Integer total(String username);
}
(六):创建UserMapper.xml
编写sql
DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hailong.dao.UserDao">
<select id="findAll" resultType="com.hailong.pojo.User">
select * from sys_user;
select>
<insert id="insertUser">
insert into sys(username,password,nickname,email,phone,address)
values (#{username},#{password},
#{nickname},#{email},
#{phone},#{address})
insert>
<update id="updateUser">
update sys_user
<set>
<if test="username != null">
username=#{username},
if>
<if test="nickname != null">
nickname=#{nickname},
if>
<if test="email != null">
email=#{email},
if>
<if test="phone != null">
phone=#{phone},
if>
<if test="phone != null">
address=#{address}
if>
set>
<where>
id = #{id}
where>
update>
<delete id="deleteById">
delete from sys_user where id = #{id}
delete>
<select id="selectPage" resultType="com.hailong.pojo.User">
select * from sys_user where username like concat('%',#{username},'%') limit #{pageNum},#{pageSize}
select>
<select id="total" resultType="java.lang.Integer">
select count(*) from sys_user where username like concat('%',#{username},'%');
select>
mapper>
(七)实现controller(此方法中含有完整的crud,在前端发送请求便可实现)
package com.hailong.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.hailong.pojo.User;
import com.hailong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
/* @Autowired
private UserDao userDao;*/
@Autowired
private UserService userService;
//测试mybatis
//查询所有数据
@GetMapping
public List<User> findUser(){
// return userDao.findAll();//使用mybatis实现的查询所有数据
//使用mybatis-plus实现查询所有数据
return userService.list();
}
//修改添加数据
@PostMapping
public boolean add(@RequestBody User user){
boolean i = userService.addoredit(user);
return i;
}
//通过id删除数据
// int i = userDao.deleteById(id);
// return i >0 ?"success":"error";//使用mybatis实现通过id删除
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id){
System.out.println("==========>"+id);
return userService.removeById(id);
}
@PostMapping("/del/batch")
public boolean deletebatch(@RequestBody List<Integer> ids){
return userService.removeByIds(ids);
}
//分页查询(通过mysql的基础实现分页查询)
//RequestParam接收?pageNum=1&pageSize=10
//结论:limit第一个参数 =(pageNum - 1)* pageSize
@GetMapping("/page")
public Map<String,Object> findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam String username){
pageNum = (pageNum - 1)* pageSize;
Map<String,Object> res = new HashMap<>();
List<User> data = userDao.selectPage(pageNum,pageSize,username);
Integer total = userDao.total(username);
res.put("data",data);
res.put("total",total);
return res;
}
}