实现功能
前端完整代码
后端接口
登录,注册,查询所有用户,根据用户名模糊查询,添加用户,更新用户,删除用户
前端
注册,登录,退出,用户增删改查,导航栏,分页
前端代码地址 https://download.csdn.net/download/2301_76809965/88215774
效果图
后端接口主要代码
Result类用于统一返回结果
JwtUtil类用户生成验证token
corsConfig处理跨域问题
Result设置统一返回结果
没有做拦截器,名字太长了写不下去,记不住以后再写
项目依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
package com.example.demo.util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
public class Result<T> {
private Integer code;
private String message;
private T data;
private long timestamp;
public Result(){
this.timestamp = System.currentTimeMillis();
}
public static <T> Result success(T data){
Result result= new Result<>();
result.setData(data);
return result;
}
public static <T> Result error(int code,String message){
Result result= new Result<>();
result.setCode(code);
result.setMessage(message);
return result;
}
}
JwtUtil类
package com.example.demo.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.sql.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtil {
//设置5h过期
private static final long EXPIRE_DATE=5*60*60*1000;
//token秘钥
private static final String TOKEN_SECRET = "147258";
//加密
public static String tokenTest (String username,String password){
String token = "";
try {
//过期时间
Date date = new Date(System.currentTimeMillis()+EXPIRE_DATE);
//秘钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//设置头部信息
Map<String,Object> header = new HashMap<>();
header.put("typ","JWT");
header.put("alg","HS256");
//携带username,password信息,生成签名
token = JWT.create()
.withHeader(header)
.withClaim("username",username)
.withClaim("password",password).withExpiresAt(date)
.sign(algorithm);
}catch (Exception e){
e.printStackTrace();
return null;
}
return token;
}
//解密
public static boolean verify(String token){
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
}
UserController控制器类
package com.example.demo.controller;
import com.example.demo.enity.User;
import com.example.demo.service.impl.UserServiceImpl;
import com.example.demo.util.JwtUtil;
import com.example.demo.util.Result;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController{
public static long time = System.currentTimeMillis();
@Autowired
private UserServiceImpl userService;
// 登录接口
@PostMapping("/login")
public Result login(@RequestBody User user){
User user1 = userService.getByUsername(user.getUsername(), user.getPassword());
if(user1==null){
return new Result<>(201,"登录失败",null,time);
}
String token = JwtUtil.tokenTest(user.getUsername(),user.getPassword());
return new Result<>(200,"登录成功",token,time);
}
//注册接口
@PostMapping("/register")
public Result register(@RequestBody User user){
Boolean flag = userService.save(user);
if(!flag){
return new Result<>(201,"注册失败",null,time);
}
return new Result<>(200,"注册成功",user.getId(),time);
}
//获取所有用户
@GetMapping("/getall")
public Result getAllUser(){
List<User> userList = userService.list();
return new Result<>(200,"获取数据成功",userList,time);
}
//模糊查询
@GetMapping("/getlikeuser")
public Result getLikeUser(@RequestParam("usernamePattern") String pattern ){
List<User> users = userService.getLikeUser(pattern);
int num = users.size();
return new Result<>(200,"共获取"+num+"条数据",users,time);
}
//添加用户
@PostMapping("/adduser")
public Result addUser(@RequestBody User user){
Boolean flag = userService.save(user);
if(!flag){
return new Result<>(201,"添加失败",null,time);
}
return new Result<>(200,"添加成功",user.getId(),time);
}
//根据id修改用户
@PostMapping("/updateuser")
public Result updateUser(@RequestBody User user){
boolean flag = userService.updateById(user);
if (!flag){
return new Result<>(201,"更新失败",null,time);
}
return new Result<>(200,"更新成功",user.getId(),time);
}
//根据id删除用户
@GetMapping("/delete")
public Result deleteById(@RequestParam("id") int id){
boolean flag = userService.removeById(id);
if (!flag){
return new Result<>(201,"删除失败",null,time);
}
return new Result<>(200,"删除成功",id,time);
}
}
corsConfig处理跨域问题
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
// .allowedOrigins("*")
.allowedOriginPatterns("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*")
.exposedHeaders("*");
}
}
前端部分代码
登录成功后在session保存token
methods:{
async login(loginFormRef){
this.$refs[loginFormRef].validate((valid)=>{
if(!valid){
this.$message.error("请输入合法的用户名或密码")
this.resetForm(loginFormRef)
return
}
})
const {data:res} = await this.$axios.post("http://127.0.0.1/user/login",this.loginForm)
if(res.code!=200){
this.$message.error("用户名或密码错误")
this.resetForm(loginFormRef)
return
}
this.$message.success("登录成功")
window.sessionStorage.setItem("token",res.data)
window.sessionStorage.setItem("username",this.loginForm.username)
this.$router.push({
name:"home",
})
},
resetForm(loginFormRef) {
this.$refs[loginFormRef].resetFields();
},
register(){
this.$router.push({
path:"/register",
})
}
},
created(){
if(this.$route.params){
this.loginForm = this.$route.params
}
}
路由守卫
除了注册登录页面,其他页面的访问都需要token
router.beforeEach((to, from, next) => {
const token = window.sessionStorage.getItem("token");
if (token && (to.path === "/login" || to.path === "/register")) {
// 如果用户已经登录,但尝试访问登录或注册页面,直接跳转到其他页面
next("/home");
} else if (to.path === "/login" || to.path === "/register") {
// 如果用户未登录,但尝试访问登录或注册页面,允许访问
next();
} else {
// 对于其他路由,需要 token 才能访问
token ? next() : next("/login");
}
});
其他的就不用说了
前端源码地址 https://download.csdn.net/download/2301_76809965/88215774