我正在调用ResourceB Inside ResourceA.
两者都使用相同的查询参数“param1”.
如何在调用ResourceB之前更改ResourceA中“param1”的值.
这是代码:
package com.example;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.sun.jersey.api.core.ResourceContext;
public abstract class MyResource {
ResponseBuilder response;
Request request;
protected String param1;
public MyResource(@QueryParam("param1") String param1, @Context Request request) {
this.param1 = param1;
this.request = request;
this.response = Response.ok();
}
}
public class ResourceA extends MyResource {
public ResourceA(String param1, Request request) {
super(param1, request);
}
@Context private ResourceContext rc;
public Response postJSON(String postData) {
JSONObject data = JSONObject.fromObject(postData);
if (data.has("resourceB")) {
ResourceB resourceB = rc.getResource(ResourceB.class);
// resourceB.setQueryParams("param1", "my new param 1");
resourceB.postJSON(data.getJSONArray("resourceB"));
}
}
}
public class ResourceB extends MyResource {
public ResourceB(String param1, Request request) {
super(param1, request);
}
public Response postJSON(JSONArray data) {
// this.params1 should not be "my new param 1"
}
}
解决方法:
如何使用ResourceContext.initResource(T资源),使用修改后的值初始化资源,并通过声明JAX-RS注释字段来控制DI提供程序注入的内容?
如果我理解你的问题,你想在找到匹配的资源方法之后修改请求上下文,或者挂钩注入并更改一些值.我不确定这是否可行.
但是,正如我所建议的,如果可以进行一些设计修改,您可以以编程方式初始化资源并利用仅注入的字段:
public Response postJSON(String postData) {
JSONObject data = JSONObject.fromObject(postData);
if (data.has("resourceB")) {
ResourceB resourceB = new ResourceB(/* pass here the modified query param */ "my new param 1");
// let the DI provider inject the JAX-RS annotated fields only
resourceB = rc.initResource(resourceB);
// resourceB.setQueryParams("param1", "my new param 1");
resourceB.postJSON(data.getJSONArray("resourceB"));
}
}
ResourceB类本身(及其超类)将声明您想要注入的注释字段,而@QueryParam(“param1”)(以及可能的其他JAX-RS感知字段)将在构造函数中声明,以便它可以没有被覆盖.
public abstract class MyResource {
ResponseBuilder response;
// this gets injected in the ResourceContext.initResource() method
@Context
Request request;
// additional JAX-RS annotated fields you would like to have injected such as
@PathParam("id")
private String pathParamId;
protected String param1;
// constructor JAX-RS annotated parameters would not get re-initialized
public MyResource(@QueryParam("param1") String param1) {
this.param1 = param1;
this.request = request;
this.response = Response.ok();
}
}