Jersey - Change the query parameter inside the resource

I am calling ResourceB Inside ResourceA.

Both use the same param1 request parameter.

How can I change the value of "param1" inside ResourceA before calling ResourceB.

Here is the code:

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"
    }
}
+4
source share
1 answer

ResourceContext.initResource(T resource), , DI, JAX-RS?
, , . , .

, , , , :

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();
    }
}
+3

Source: https://habr.com/ru/post/1626994/


All Articles