1.认证请求
request.js页面
import axios from "axios";
import {Message} from "element-ui";
import router from "@/router";
function request(url,data,method="post"){
//promise表示承诺,将来我会执行什么,里面是一个方法,方法有两个参数
return new Promise((resolve,reject)=>{
axios({
method,
url:'http://localhost:8080/'+url,
data,
headers:{'Authorization':localStorage.token},
}).then( (response)=> {
if (response.data.success){
resolve (response.data.data);
}else {
Message.error(response.data.message);
console.info(response.data.message)
router.push('/login')
reject();
}
})
.catch( (error) =>{
Message.error("网络故障"+error);
router.push('/login')
reject();
});
})
}
export default request;
拦截器里面做跨域预检
package cn.hx.property.interceptor;
import cn.hx.property.entity.User;
import cn.hx.property.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginInterceptor implements HandlerInterceptor {
public static final String tokenName = "Authorization";
@Autowired
RedisUtil<User> redisUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
//request.getSession() 前端和后端不再一个项目时反请求是跨域的,跨域时不能携带 cookie
String token = request.getHeader(tokenName);
String method = request.getMethod();
if (method.equals("OPTIONS")){//跨域时浏览器会发送一个请求,(预检请求,他的请求方式是OPTIONS)
//一旦请求返回不是200,浏览器就认为该请求不允许跨域,浏览器就不会发生真正的请求
return true;
}
User user = redisUtil.get("session:" + token);
if (user!=null){//用户请求参数里面携带的token在redis里面有
return true;
}
throw new RuntimeException("用户未登录");
}
}
做页面表格,发axios请求
分页的后台代码
controller改一下
service跟serviceImpl也要改
UserManager.vue页面
<template>
<div>
<h1>用户管理</h1>
<!-- 查询栏-->
<el-form :inline="true" :model="formInline" size="medium" >
<el-form-item>
<el-button type="primary" size="medium">添加</el-button>
</el-form-item>
<el-form-item label="用户名">
<el-input v-model="formInline.username" placeholder="用户名"></el-input>
</el-form-item>
<el-form-item label="电话">
<el-input v-model="formInline.mobile" placeholder="电话"></el-input>
</el-form-item>
<el-form-item label="邮箱">
<el-input v-model="formInline.email" placeholder="邮箱"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" size="small" @click="onSubmit">查询</el-button>
</el-form-item>
</el-form>
<!-- 页面表格-->
<!-- @sort-change="sortChange",sortable="custom"用来做排序-->
<el-table :data="tableData" @sort-change="sortChange">
<el-table-column sortable="custom" prop="userId" label="用户ID" width="140">
</el-table-column>
<el-table-column sortable="custom" prop="username" label="用户名" width="120">
</el-table-column>
<el-table-column sortable="custom" prop="mobile" label="手机号">
</el-table-column>
<el-table-column sortable="custom" prop="email" label="邮箱">
</el-table-column>
<el-table-column sortable="custom" prop="createTime" label="创建时间">
</el-table-column>
<el-table-column label="状态">
<template v-slot="scope"><!--状态栏修改按钮 插槽表达式-->
<el-switch
@change="switchChange(scope.row)"
v-model="scope.row.status"
active-color="#13ce66"
inactive-color="#ff4949"
:active-value="1"
:inactive-value="0">
</el-switch>
</template>
</el-table-column>
<el-table-column label="操作">
<el-button type="info" size="mini" >修改</el-button>
<el-button type="danger" size="mini">删除</el-button>
</el-table-column>
</el-table>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="page"
:page-sizes="[2, 10, 20, 50]"
:page-size="size"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</template>
<script>
import request from "@/util/request";
export default {
name: "UserManger",
created() {
this.loadData();
},
data() {
return {
page: 1,
size: 2,
tableData: [],
total: 3,
formInline:{}
}
}, methods: {
async loadData() {
let data = await request(`user/findAll?page=${this.page}&size=${this.size}`, {}, )
this.tableData = data.list;
this.total=data.total;
},
handleSizeChange(obj) {
this.size = obj;
this.loadData();
},
handleCurrentChange(obj) {
this.page = obj;
this.loadData();
},
async onSubmit(){
let data = await request(`user/findAll?page=${this.page}&size=${this.size}`, this.formInline)
this.tableData = data.list;
this.total=data.total;
},
async sortChange(obj){
console.info(obj)
let orderBy
if (obj.order === "ascending"){
orderBy = obj.prop + ' asc'
}else {
orderBy = obj.prop + ' desc'
}
let data = await request(`user/findAll?page=${this.page}&size=${this.size}&orderBy=${orderBy}`, this.formInline)
this.tableData = data.list;
this.total=data.total;
},
//上面传过来一个对象,但是不需要他的全部属性,打一个{}解构赋值:只取里面的XXX属性
async switchChange({userId,status}){
let data = await request("user/update",{userId,status})
if (data){
this.$message("修改成功")
}
}
}
}
</script>
<style scoped>
</style>
aop分页
@Component //放到容器内
@EnableAspectJAutoProxy
@Aspect
public class PropertyAspect {
//将实体类字段转换对应的数据库字段,参数由前端发过来
private String getOrderBy(String in){
StringBuffer stringBuffer = new StringBuffer();
char[] chars = in.toCharArray();
for (char c : chars) {
if (c <= 'Z' && c >= 'A'){
stringBuffer.append('_');
stringBuffer.append((char)(c + 32));
}else {
stringBuffer.append(c);
}
}
return stringBuffer.toString();
}
//ProceedingJoinPoint 是针对 Around 环绕通知的形参,它可以获取原方法所有的细节
//execution 表达式 任意返回* cn.hx.property.service.impl.*.queryAll(..)
@Around("execution(* cn.hx.property.service.impl.*.queryAll(..))")
public Object pageAop(ProceedingJoinPoint joinPoint) throws Throwable {
//从 request里面获取page和size参数 orderBy
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String page = request.getParameter("page");
String size = request.getParameter("size");
String orderBy = request.getParameter("orderBy");
//分页后缓存到Redis的类型不能是 Page,必须是PageInfo,因为PageInfo才能保留分页信息
if (StringUtils.hasText(page) && StringUtils.hasText(size)) {
Page<Object> objects = PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(size), StringUtils.hasText(orderBy) ? getOrderBy(orderBy) : null);
joinPoint.proceed();//调用目标方法
return new PageInfo<>(objects);
}
Object object = joinPoint.proceed();//调用目标方法
return object;
}