【发布时间】:2012-04-12 05:24:50
【问题描述】:
我正在尝试将 ExtJS 与 JAX-RS 集成。我用 POJOMappingFeature 设置了 Jersey,它工作正常。但我想摆脱胶水代码。每个类现在看起来像这样:
@Path("/helloworld")
public class A {
@POST
@Produces(MediaType.APPLICATION_JSON)
public final ExtJsRestOutput createAction(ExtJsRestInput<B> toCreate) {
try {
final B created = toCreate.getData();
// logic
return new ExtJsRestDataOutput<B>(created);
} catch (Exception e) {
return new ExtJsRestFailure();
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public final ExtJsRestOutput readCollectionAction() {
try {
final List<B> readCollection;
//logic
return new ExtJsRestDataOutput<List<B>>(readCollection);
} catch (Exception e) {
return new ExtJsRestFailure();
}
}
@PUT
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public final ExtJsRestOutput updateAction(ExtJsRestInput<B> toUpdate) {
try {
final B udpated = toUpdate.getData();
// logic
return new ExtJsRestDataOutput<B>(udpated);
} catch (Exception e) {
return new ExtJsRestFailure();
}
}
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public final ExtJsRestOutput readAction(@PathParam("id") Integer id) {
try {
final T read;
// logic
return new ExtJsRestDataOutput<B>(read);
} catch (Exception e) {
return new ExtJsRestFailure();
}
}
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public final ExtJsRestOutput deleteAction(@PathParam("id") Integer id) {
try {
// logic
return new ExtJsRestSuccess();
} catch (Exception e) {
return new ExtJsRestFailure();
}
}
}
我尝试通过继承来解决这个问题,结果变成了这样:
public abstract class ExtJsRestAction<T> {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public final ExtJsRestOutput readAction(@PathParam("id") Integer id) {
try {
final T read = read(id);
return new ExtJsRestDataOutput<T>(read);
} catch (Exception e) {
LOG.error("blad wywolania read", e);
return new ExtJsRestFailure("FAIL");
}
}
abstract public T read(Integer id) throws Exception;
// ... similar for the other methods
}
这使得扩展类干净且与 ExtJS 无关:
@Path("/helloworld")
public class BAction extends ExtJsRestAction<B> {
B create(B toCreate){
// logic
}
B read(Integer id){
// logic
}
// and so on...
}
这样会很好,但是当路径看起来像这样时会出现问题:
@Path("/helloworld/{anotherId}")
没有(简单的)方法可以访问 anotherId。
我不知道我是否应该寻找解决方案。有没有办法编写一个拦截器类而不是这个基类来为 ExtJS 打包/解包对象?或者,也许您可以推荐一个更好的解决方案来将 ExtJS 与 Java 集成。我使用的是 Struts 2,当我添加自定义拦截器时它与 JSON 配合得很好,但我希望能够使用 JAX-RS API 做得更好。
【问题讨论】:
-
您的问题已经过去一年了。你最后选择了什么?
-
我们重新使用 Struts 2。