具有子资源的JAX-RS(Jersey)资源类可以拆分为两个类吗?
目前,我将两者合并为一个资源类:
@Path("/session")
public class SessionResource {
@POST
@Produces("application/xml")
public Response createSession() {
...
ResponseBuilder builder = Response.created(URI.create("/session/" + new Date().toString()));
return builder.build();
}
@DELETE
public Response destroySession() {
...
ResponseBuilder builder = Response.noContent();
return builder.build();
}
// TrustedSession sub-resource
@POST
@Path("/trusted")
@Produces("application/xml")
public Response createTrustedSession() {
...
ResponseBuilder builder = Response.created(URI.create("/session/" + new Date().toString()));
return builder.build();
}
@DELETE
@Path("/trusted")
public Response destroyTrustedSession() {
...
ResponseBuilder builder = Response.noContent();
return builder.build();
}
}
我想将TrustedSession代码移动到单独的Resouce:
@Path("/session/trusted")
public class createSession {
@POST
@Produces("application/xml")
public Response createTrustedSession() {
...
ResponseBuilder builder = Response.created(URI.create("/session/trusted/" + new Date().toString()));
return builder.build();
}
@DELETE
public Response destroySession() {
...
ResponseBuilder builder = Response.noContent();
return builder.build();
}
}
在编译代码时,资源路由不起作用。
答案 0 :(得分:3)
如果要在单独的类中处理子资源,则必须省略主资源类中方法的请求方法指示符。
尝试为受信任的会话创建子类。在主资源类中返回此类的实例,如下所示:
@Path("/session")
public class SessionResource {
// Note that the request method designator is omitted.
@Path("/trusted")
public TrustedSession getTrustedSession() {
return new TrustedSession();
}
}
在子资源的类中,您只需要注释请求方法:
public class TrustedSession {
@POST
@Produces("application/xml")
public Response createTrustedSession() {
URI uri = URI.create("/session/trusted/" + new Date().toString());
return Response.created(uri).build();
}
@DELETE
public Response destroySession() {
return Response.noContent().build();
}
}
在The Java EE 6 Tutorial中(简要)解释了子资源定位器。
顺便说一句:使用javax.ws.rs.core.UriBuilder可以更方便,更安全地构建URI,即使用fromSesource(Class)方法。