目录
前言:
所需知识 Springboot Springsecurity,不了解的先看这篇
(23条消息) spring security 前后端分离 进行用户验证 权限登陆的实现代码(看不懂??直接cv)_代码大帝的博客-CSDN博客
前后端分离小案例。 页面不够精美,但是对于初学者而言。干货满满,大多数人的博客都只是简单的实现vue的集合修改,完全没有实际开发意义,也许我的也好不到哪去,但是却是实打实的操作数据库。
运用了elementUI vue脚手架的增删改查小案例可以看
(27条消息) 前后端分离 element UI spring security 脚手架 实现简单的增删改查小案例_代码大帝的博客-CSDN博客
登陆Vue:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="./js/axios.min.js"></script>
<script src="./js/qs.js"></script>
<script src="./js/vue.js"></script>
</head>
<body>
<div id="login">
<p>
<input type="text" v-model="user.username">
</p>
<p>
<input type="password" v-model="user.password">
</p>
<button v-on:click="login()">登陆</button>
<button>测试接口</button>
</div>
</body>
<script>
new Vue({
el: "#login",
data: {
//登陆用户
user: {"username": "", "password": ""},
msg: {}//登陆错误
},
methods: {
login() {
console.log(this.user);
//使用axios向后台发送一个post请求
axios.post("http://localhost:8080/login",
Qs.stringify(this.user))
.then(result => {
console.log("返回结果:" + JSON.stringify(result));
if (result.data.status == 'OK') {
//把token保存到本地
localStorage.setItem("token", result.data.data.token);
//跳转到权限管理
location.href = "permission.html";
}
})
.catch(err => {
console.log("出现错误:" + JSON.stringify(err));
});
},
//测试访问后台接口
testGet() {
//访问后台接口时,需要在请求头中携带token
axios.get("http://localhost:8080/hello1", {"headers": {"Authorization": localStorage.getItem("token")}})
.then(result => {
console.log("返回结果:" + JSON.stringify(result));
});
}
}
})
</script>
</html>
1.发送请求给服务器,进行用户验证
2.返回结果给登陆界面
3.跳转到permission.html
主要功能页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/axios.min.js"></script>
<script src="js/qs.js"></script>
<script src="js/vue.js"></script>
</head>
<body>
<div id="permission">
<table width="500px" cellpadding="10px" border="1px" cellspacing="0px">
<tr>
<th>编号</th>
<th>名称</th>
<th>URL</th>
<th>PID</th>
<th>描述</th>
<th>图标</th>
<th>顺序</th>
<th>操作</th>
</tr>
<tr v-for="per in permissions">
<td>{{per.id}}</td>
<td>{{per.name}}</td>
<td>{{per.description}}</td>
<td>{{per.url}}</td>
<td>{{per.pid}}</td>
<td>{{per.icon}}</td>
<td>{{per.sort}}</td>
<td>
<button v-on:click="update(per.id)"></button>
</td>
</tr>
</table>
<div>
id <input type="text" v-model="permission.id"><br>
名字<input type="text" v-model="permission.name"><br>
<input type="text" v-model="permission.description"><br>
<input type="text" v-model="permission.url"><br>
<input type="text" v-model="permission.pid"><br>
<input type="text" v-model="permission.icon"><br>
<input type="text" v-model="permission.sort"><br>
<button v-on:click="update(permission.id)">修改</button>
</div>
<button v-for="n in pageCount" v-on:click="loadPermissionPage(n)">{{n}}</button>
</div>
</body>
<script>
new Vue({
el: "#permission",
data: {
permissions: [],//权限集合
permission: {},//单个权限
current: 1,
pageSize: 10,
pageCount: 0
},
methods: {
loadPermissionPage(current) {
this.current = current;
// axios.get("http://localhost:8080/permissions/page?current="+this.current+"&pageSize=10",{"header":{"Authorization":localStorage.getItem("token")}})
axios.get("http://localhost:8080/permissions/page?current=" + this.current + "&pageSize=" + this.pageSize,
{"headers": {"Authorization": localStorage.getItem("token")}})
.then(result => {
if (result.data.status == "OK") {
this.permissions = result.data.data.records;
this.pageCount = result.data.data.pages;
}
});
},
update(id) {
let permission;
for (let i = 0; i < this.permissions.length; i++) {
if (id == this.permissions[i].id) {
//表示重复id 进行修改
// permission.id = this.permission.id;
// permission.name = this.permission.name;
// permission.description = this.permission.description;
// permission.url = this.permission.url;
// permission.pid = this.permission.pid;
// permission.icon = this.permission.icon;
// permission.sort = this.permission.sort;
axios.put("http://localhost:8080/permission",
Qs.stringify(this.permission)
, {"headers": {"Authorization": localStorage.getItem("token")}})
.then(result => {
if (result.data.status == "OK") {
console.log(permission)
}
});
} else if (id > this.permissions.length) {
axios.post("http://localhost:8080/permission",
Qs.stringify(this.permission)
, {"headers": {"Authorization": localStorage.getItem("token")}})
.then(result => {
if (result.data.status == "OK") {
console.log(permission)
}
});
}
}
}
},
mounted() { //生命周期函数 界面挂载完成
this.loadPermissionPage(1);
}
})
</script>
</html>
解释重要内容
1. mounted() { //生命周期函数 界面挂载完成
this.loadPermissionPage(1);
}在进入页面的时候就执行方法渲染
2. axios.post("http://localhost:8080/permission",
Qs.stringify(this.permission)
, {"headers": {"Authorization": localStorage.getItem("token")}})发送请求需要携带token进行验证
3.发送请求的重要步骤
el data methods then
ServiceImpl代码:
package com.dmdd.javasecuritypractice.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dmdd.javasecuritypractice.entity.Permission;
import com.dmdd.javasecuritypractice.mapper.PermissionMapper;
import com.dmdd.javasecuritypractice.service.IPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author xray
* @since 2023-01-31
*/
@Service
@Slf4j
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
private static final String KEY = "User-";
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private PermissionMapper permissionMapper;
// @Cacheable(cacheNames = "permission",key = "T(String).valueOf(1)")
@Override
public List<String> selectAllAuthorization() {
return permissionMapper.selectAllAuthorization();
}
//分页查询
// @Cacheable(cacheNames = "selectAllAuthorizationByPage",key = "T(String).valueOf(#page.current)")
@Override
public IPage<Permission> selectAllAuthorizationByPage(IPage<Permission> page) {
return permissionMapper.selectAllAuthorizationByPage(page);
}
// @Cacheable(cacheNames = "selectAuthorizationById",key = "T(String).valueOf(#id)")
@Override
public List<Permission> selectAuthorizationById(Long id) {
return permissionMapper.selectAuthorizationById(id);
}
// @Cacheable(cacheNames = "add",key = "T(String).valueOf(#permission.id)")
@Override
public Permission add(Permission permission) {
boolean save = this.save(permission);
if (save) {
return permission;
}
return null;
}
// @Cacheable(cacheNames = "delete",key = "T(String).valueOf(#id)")
@Override
public int delete(Long id) {
boolean b = this.removeById(id);
if (b) {
return 1;
}
return 0;
}
// @Cacheable(cacheNames = "update",key = "T(String).valueOf(#permission.id)")
@Override
public int update(Permission permission) {
boolean b = this.saveOrUpdate(permission);
if (b) {
return 1;
}
return 0;
}
}
控制器代码:
package com.dmdd.javasecuritypractice.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmdd.javasecuritypractice.entity.Permission;
import com.dmdd.javasecuritypractice.service.IPermissionService;
import com.dmdd.javasecuritypractice.service.IUserService;
import com.dmdd.javasecuritypractice.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class eduController {
@Autowired
private IUserService userService;
@Autowired
private IPermissionService service;
@PreAuthorize("hasAuthority('仓库管理')")
@RequestMapping("/permissions")
public ResponseResult permissions() {
List<String> strings = service.selectAllAuthorization();
String join = String.join(",", strings);
return ResponseResult.ok(join);
}
@PreAuthorize("hasAuthority('仓库管理')")
@RequestMapping("/permissions/page")
public ResponseResult<IPage<Permission>> permissionsPage(@RequestParam(required = false,defaultValue = "1") Long current,
@RequestParam(required = false,defaultValue = "5")Long pageSize) {
Page<Permission> permissionPage = new Page<>();
permissionPage.setCurrent(current);
permissionPage.setSize(pageSize);
IPage<Permission> permissionIPage = service.selectAllAuthorizationByPage(permissionPage);
// List<Permission> records = permissionIPage.getRecords();
String all = "权限:";
// for (Permission permission:records){
// all+= permission.getName();
// }
// List<Permission> collect = records.stream().limit(pageSize).collect(Collectors.toList());
// return collect;
return ResponseResult.ok(permissionIPage);
}
//按id查询权限
@PreAuthorize("hasAuthority('仓库管理')")
@RequestMapping("/permission/{id}")
public ResponseResult<List<Permission>> permissionById(@PathVariable Long id) {
System.out.println(id);
List<Permission> permissions = service.selectAuthorizationById(id);
System.out.println(permissions);
return ResponseResult.ok(permissions);
}
@PreAuthorize("hasAuthority('仓库管理')")
@PostMapping("/permission")
public ResponseResult<Permission> add(Permission permission) {
Permission add = service.add(permission);
return ResponseResult.ok(add);
}
@PreAuthorize("hasAuthority('仓库管理')")
@DeleteMapping("/permission/{id}")
public ResponseResult<Integer> delete(@PathVariable Long id) {
int delete = service.delete(id);
return ResponseResult.ok(delete);
}
@PreAuthorize("hasAuthority('仓库管理')")
@PutMapping("/permission")
public ResponseResult<Integer> update(Permission permission) {
int update = service.update(permission);
return ResponseResult.ok(update);
}
}
本博客可以实现跨域,简单的前后端分离查询,新增与修改,详情代码可以通过我的gitee下载
jly ThreeHomeWork: 大家随便用123456