基于Vue和springBoot的登录模块设计

本文详细介绍了如何使用Vue.js前端框架和SpringBoot后端框架配合,实现登录功能。包括Vue登录页面设计、axios发送登录请求、后端登录接口及验证逻辑。登录成功后,将JWT类型的token保存在cookie中,前端通过路由拦截器验证登录状态,并从cookie中获取用户信息。此外,还展示了如何在Vue组件中获取并显示用户信息。
摘要由CSDN通过智能技术生成

基于Vue和springBoot的登录模块设计

1.登录页面设计

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mPlvLyMd-1602665785189)(C:\Users\54729\AppData\Roaming\Typora\typora-user-images\1602652478868.png)]

2.发送登录请求

使用的是axios发送请求

需求是,将填写的username 和password传递到登录接口,成功,返回token类型的cookie, 并跳转到home页面;失败,则弹出“登录失败”的提示信息。具体方法如下:

 login(){
      //表单预验证npm
      this.$refs.loginFormRef.validate( async valid=>{
        if (!valid) return;
        const res=await this.$http.post("login",this.loginForm);
        console.log(res)
        if (!res.data){
          this.$message.error("登录失败!")
        }else {
          this.$message.success("登录成功!")
          this.$router.push("/home")
        }
      })
    }

注意,因为使用的axios发送请求,所以在 main.js文件中要做一下关于 axios 的默认配置。配置如下:

import axios from 'axios'
//配置请求的根路径
axios.defaults.baseURL='http://localhost/'
//设置后,返回的cookie会保存在浏览器,否则不会
axios.defaults.withCredentials=true
Vue.prototype.$http= axios

3.登录接口设计

controller设计

方法:

@Controller
public class TestController {
    @Autowired
    private TestService testService;

    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("login")
    public ResponseEntity<Boolean> login(@RequestBody User user, HttpServletResponse response, HttpServletRequest request){
        //调用 service,传入user对象,返回生成的 token 字符串
        String token = this.testService.findByUser(user);
        //判断
        if (StringUtils.isBlank(token)){
            System.out.println("找不到该账户!");
            return ResponseEntity.ok(false);
        }

        //使用 cookieUtils.setCookie方法,就可以把 jwt 类型的token 设置给 cookie
  CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,jwtProperties.getExpire()*60,"utf-8",true);
        return ResponseEntity.ok(true);
    }
}

service设计

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class TestService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    public String findByUser(User user){
        //数据库查询User对象
        User user_find = this.userMapper.selectOne(user);
        if (user_find==null){
            return null;
        }
        
        //初始化荷载信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user_find.getId());
        userInfo.setUsername(user_find.getUsername());
        
        try {
            //使用JwtUtils,生成token字符串,并返回
            return JwtUtils.generateToken(userInfo,jwtProperties.getPrivateKey(),jwtProperties.getExpire());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}

mapper设计

public interface UserMapper extends Mapper<User> {
}

utils

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tIhBTZsQ-1602665785193)(C:\Users\54729\AppData\Roaming\Typora\typora-user-images\1602665711015.png)]

添加登录验证功能

用户可以在无登录的情况下访问登录页面,访问其他页面,会跳转到登录页面;登录后,可以访问其他页面,同时登录后访问其他页面时,要返回从token中解析的用户信息

1.配置路由文件index.js

添加过滤方法 router.beforeEach() ,每次进行路由跳转时,都会经过此方法,判定后决定是否进行跳转

router.beforeEach(async(to,from,next)=>{
    //跳转到登录页面,则放行
  if (to.path==='/login') return next();
  try {
      //不为登录页面,则去后台接口判定是否进行登录,
      //返回结果为空,跳转到登录页面;不为空,则放行
    const { data } = await axios.get('/verify')
  } catch (e) {
     return next('/login');
  }
  next()

})

2.后台接口设计

@GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUserInfo(
            @CookieValue("SJ_TOKEN") String token,
           HttpServletRequest request,
           HttpServletResponse response){
        UserInfo userInfo = null;
        try {
            //根据获取的cookie和本地公钥解析出 userInfo 信息
            userInfo=JwtUtils.getInfoFromToken(token,jwtProperties.getPublicKey());
            if (userInfo==null){
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            //刷新jwt过期时间;本质是重新生成jwt
             token =JwtUtils.generateToken(userInfo,this.jwtProperties.getPrivateKey(),this.jwtProperties.getExpire());
            //刷新cookie的过期时间
            CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,jwtProperties.getExpire()*60,"utf-8",true);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        return ResponseEntity.ok(userInfo);
    }

3.登录后,页面获取userInfo信息

在vue组件中定义初始化方法,当页面初始化时,从后台接口中解析出用户信息返回到页面

<script>
  export default {
    name: 'Home',
    data(){
      return{
        userInfo:{
          id:"afsdf",
          username:"ggg"
        }
      }
    },
    async created () {//初始化方法,页面初始化时,从后台返回userInfo数据
      const res = await this.$http.get("/verify");
      console.log(res.data)
      this.userInfo.id=res.data.id
      this.userInfo.username=res.data.username

    }
  }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值