异常处理及前端页面授权认证

本文介绍如何使用Shiro进行权限管理,包括异常处理、自定义提示错误、前端页面的授权认证等。通过具体实例展示了不同角色登录后所见页面的区别,并提供了实现这些功能的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、异常处理

当用户登录后,做出了没有权限的操作,显示自定义提示错误!

1.1、在controller下新建PermissionsException类,处理特殊异常

package com.massimo.shiro.controller;

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class PermissionsException {
    @ResponseBody
    @ExceptionHandler(UnauthorizedException.class)
    public String unauthorizedException(Exception e){
        return "无权限";
    }

    @ResponseBody
    @ExceptionHandler(AuthorizationException.class)
    public String authorizationException(Exception e){
        return "权限认证失败";
    }
}

1.4、用户李四登录测试

在这里插入图片描述
在这里插入图片描述

二、前端页面授权认证

当不同的角色登录,所看到的页面也是不同的

2.1、添加依赖

配置Thymeleaf与Shrio的整合依赖

<dependency>
      <groupId>com.github.theborakompanioni</groupId>
      <artifactId>thymeleaf-extras-shiro</artifactId>
      <version>2.0.0</version>
</dependency>

2.2、在ShiroConfig中添加新配置

    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

2.3、修改main.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Shiro登录认证后主页面</h1>
<br>
登录用户为:<span th:text="${session.user}"></span>
<br>
<a href="/logout">登出</a>
<br>
<a shiro:hasRole="admin" href="/myController/userLoginRoles">测试授权-角色验证</a>
<br>
<a shiro:hasPermission="user:delete" href="/myController/userPermissions">测试授权-权限验证</a>
</body>
</html>

2.4、登录测试

用户张三登录
在这里插入图片描述

用户李四登录
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值