@RequiresPermissions 控制权限的异常处理以及Ajax方式请求时返回json

本文介绍如何使用Shiro框架进行权限控制,并针对Ajax请求实现未登录或无权限时的JSON反馈。通过自定义BaseController类,实现了统一的异常处理机制。

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

参考http://www.mamicode.com/info-detail-1746942.html

例如使用到注解: 
@RequiresPermissions 来控制是否有对应权限才可以访问 
@RequiresUser 来控制是否存在用户登录状态才可以访问

想了解Shiro是如何通过注解来控制权限的,可以查看源码 AopAllianceAnnotationsAuthorizingMethodInterceptor,其构造方法中添加了几个对应的权限注解方法拦截器(这里不做详细阐述)。

用户在请求使用这些注解方式控制的方法时,如果没有通过权限校验。Shiro 会抛出如下两组类型的异常。

登录认证类异常 UnauthenticatedException.class, AuthenticationException.class 
权限认证类异常 UnauthorizedException.class, AuthorizationException.class 
(每个具体的异常对应哪个注解,大家查看源码了解一下)

言归正传,直接上代码,通过代码来说明本文目的 “做Ajax请求的时候,如果请求的URL是被注解权限控制的,在没有权限或者登陆失效的情况下,如果获得JSON方式的返回结果(如果用户没有登录,大多数都是直接跳转到登录页面了)”。

通过一个 BaseController 来统一处理,然后被其他 Controller 继承即可,对于JSON和页面跳转,我们只需要做一个Ajax判断处理即可。

代码如下:

/**
 * BaseController
 *
 * @author 单红宇(365384722)
 * @myblog http://blog.youkuaiyun.com/catoop/
 * @create 2017年4月4日
 */
public abstract class BaseController {

    /**
     * 登录认证异常
     */
    @ExceptionHandler({ UnauthenticatedException.class, AuthenticationException.class })
    public String authenticationException(HttpServletRequest request, HttpServletResponse response) {
        if (WebUtilsPro.isAjaxRequest(request)) {
            // 输出JSON
            Map<String,Object> map = new HashMap<>();
            map.put("code", "-999");
            map.put("message", "未登录");
            writeJson(map, response);
            return null;
        } else {
            return "redirect:/system/login";
        }
    }

    /**
     * 权限异常
     */
    @ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
    public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
        if (WebUtilsPro.isAjaxRequest(request)) {
            // 输出JSON
            Map<String,Object> map = new HashMap<>();
            map.put("code", "-998");
            map.put("message", "无权限");
            writeJson(map, response);
            return null;
        } else {
            return "redirect:/system/403";
        }
    }

    /**
     * 输出JSON
     *
     * @param response
     * @author SHANHY
     * @create 2017年4月4日
     */
    private void writeJson(Map<String,Object> map, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            out.write(JsonUtil.mapToJson(map));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
public class WebUtilsPro {

    /**
     * 是否是Ajax请求
     *
     * @param request
     * @return
     * @author SHANHY
     * @create 2017年4月4日
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }
}

下面是一个普通的 Controller

@Controller
@RequestMapping
public class PageController extends BaseController{

    @RequiresUser
    @RequestMapping(value="/main", method=RequestMethod.GET)
    public String main(Model model){
        return "main";
    }

    @RequiresUser
    @RequestMapping(value="/getData", method=RequestMethod.POST)
    @ResponseBody
    public List<String> getData(Model model){
        List<String> list = new ArrayList<>();
        list.add("data1");
        list.add("data2");
        return list;
    }

}

当我们使用 ajax 方式去请求 /getData 时,如果用户没有登录。则会返回对应没有登录的JSON结果。 
页面在做ajax请求时候,发现用户没有登录,可能需要根据响应结果做对用的页面交互处理,而不是暴力的直接重定向到登录页面了。


在泛微OA中,我想通过ecode平台实现在流程中新增一个按钮,代码如下,为什么没有效果:const { WeaTools, WeaSlideModal } = ecCom; class testComponent extends React.Component { constructor(props) { super(props); this.state = { info: { name: '' }, jsonData: {}, currentObj: {} }; } componentDidMount() { window.WfCustomInfoRef = this; this.getData(); } getData() { const data = { name: "John1", age: 25 }; fetch('/api/workflow/test/getInfo2', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { this.setState({ jsonData: data }, () => { console.log(this.state.jsonData); }); }) .catch(error => { console.error('请求出错:', error); }); } render() { const { info, jsonData, currentObj } = this.state; return ( <div> 添加的自定义内容2{jsonData.username} <button type= "primary" onClick={()=>{ var requestId = WfForm.getBaseInfo().requestid; jQuery.ajax({ type: "POST", url: "http://192.168.10.129:8089/workflow/request/GetSAPDataAjax.jsp", data: {'requestid':requestId, 'method':"QZgd"}, //dataType: 'json', success:function(data){ console.log(data) // alert(data) }, error:function(data){ alert("系统出现问题,请联系管理员!"); } }) }}>按钮</button> {jsonData.test} </div> ); } } ecodeSDK.setCom('${appId}', 'testComponent', testComponent);在对应的节点通过单元格id控制按钮显示位置: var params = { domId:'btnUpdate',//渲染位置的fieldId id:'eaf7e8a2fe824894a6f81e7d112530c1',//appid name:'testComponent',//调用的组件名称,在setCom中定义的 cb:function(){ //渲染完成后的回调 }, noCss:true, props:{} }
最新发布
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值