2013-01-18 81 views
1

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

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

现在,在我的功能扩展ServerResource,我可以做这样的事情很容易地提取{SID}

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

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

任何帮助将不胜感激!

感谢

回答

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. 任何子类的ServerResourcedoInit()调用带有注释的任何方法被调用之前@Get/@Post/...

  2. (小心)如果您不使用此声明:

    getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); 
    

    也就是说,如果你不设置状态响应的一个错误,则注释的方法,用@Get/@Post/@Put/...将调用!但是如果你的程序设置响应错误状态的状态,那么@Get/@Post/@Put/......不会得到执行,最终用户将看到所代表的错误消息:

    getResponse().setEntity(/*Representation carrrying message for unauthorized user*/); 
    
+0

谢谢阿布舍克!这是一个很好的答案。我给了这一枪。 – kvheerden