1

我正在开发一个 RESTlet API (JAVA),并且我创建了一个自定义授权过滤器,我在将所有请求传递给我的路由器之前运行它。在我的请求中,我总是将会话 ID 作为请求属性传递,例如

    http://localhost:8080/myAPI/{sid}/someResource/

现在,在我扩展ServerResource的函数中,我可以做这样的事情来轻松提取{sid}

    String sid = (getRequestAttributes().containsKey("sid")) ? getRequestAttributes().get("sid").toString() : "";

我的问题是,在我的扩展过滤器的授权函数中(授权函数不是通过路由器调用,而是在我的主createInboundRoot()函数中调用),我不能使用相同的方法来提取{sid}。我已经使用request.getResourceRef().getSegments()的字符串操作创建了一个解决方法,但是必须有更好的方法吗?

任何帮助将不胜感激!

谢谢

4

1 回答 1

3

可以ServerResource. 像这样:

public class CommonParentResource extends ServerResource
{
    // class definition
}

然后重写里面的ServerResource类的doInit()方法。

public class CommonParentResource extends ServerResource
{
    public void doInit()
    {
        boolean authorized=false;

        String sid = getRequestAttributes().containsKey("sid") ? (String)getRequestAttributes().get("sid") : StringUtils.EMPTY;

        // Authorization logic here.

        if(!authorized)//after authorization process completed.
        {
            getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
            getResponse().setEntity(/*Representation carrrying message for unauthorized user*/);
        }
    }
}

ServerResource现在,您要执行此授权检查的任何新子类都必须扩展CommonParentResource该类。像这样:

public class FriendsListResource extends CommonParentResource
{
    @Get
    //......
}

这里有两点很重要:

  1. doInit()的任何子类ServerResource在调用任何带有 // ... 注释的方法之前@Get@Post调用

  2. (注意)如果您不使用此语句:

    getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
    

    即,如果您没有设置对错误响应状态,那么带有/// ...注释的方法将被调用!但是如果你的程序将响应的状态设置为错误状态,那么// / ... 将不会被执行,最终用户将看到如下所示的错误消息:@Get@Post@Put@Get@Post@Put

    getResponse().setEntity(/*Representation carrrying message for unauthorized user*/);
    
于 2013-01-18T10:50:01.217 回答