您可以为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
//......
}
这里有两点很重要:
doInit()
的任何子类ServerResource
在调用任何带有 // ... 注释的方法之前@Get
被@Post
调用
(注意)如果您不使用此语句:
getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
即,如果您没有设置对错误的响应状态,那么带有/// ...注释的方法将被调用!但是如果你的程序将响应的状态设置为错误状态,那么// / ... 将不会被执行,最终用户将看到如下所示的错误消息:@Get
@Post
@Put
@Get
@Post
@Put
getResponse().setEntity(/*Representation carrrying message for unauthorized user*/);