将参数传递给Jersey资源

时间:2014-12-11 20:39:01

标签: java rest jersey jetty jax-rs

如何从TestRes资源中检索mapProp?

我正在使用嵌入码头的平针织物。

    Map<String,Object> mapProp= new HashMap<String,Object>()
    mapProp.put("message","HelloWorld")

    URI baseUri = UriBuilder.fromUri("http://localhost/").port(9998).build();
    ResourceConfig config = new ResourceConfig(TestRes.class);
    config.addProperties(mapProp)
    Server server = JettyHttpContainerFactory.createServer(baseUri, config);

由于

2 个答案:

答案 0 :(得分:1)

实际上,TestRes类的更多代码会很有用。

但我想,你要找的是@PathParam

例如:

@Path("yourPath/{map})
public void getMyMap(@PathParam("map")String map){
//Do something
}

将切换参数图。

也很好地解释了here

答案 1 :(得分:1)

您可以使用javax.ws.rs.core.Configuration注释在资源类中注入@Context。使用Configuration,您可以致电getProperties()以获取您在ResourceConfig

中设置的属性地图

这是一个完整的例子

import java.util.*;
import javax.ws.rs.*;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.*;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;

public class TestConfiguration extends JerseyTest {

    @Path("/configuration")
    public static class ConfigurationResource {

        @Context
        Configuration config;

        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public Response getConfig() {
            StringBuilder builder = new StringBuilder("============\n");
            Map<String, Object> props = config.getProperties();

            for (Map.Entry<String, Object> entry : props.entrySet()) {
                builder.append(entry.getKey()).append(" : ")
                        .append(entry.getValue()).append("\n");
            }
            builder.append("=============");
            return Response.ok(builder.toString()).build();
        }
    }

    @Override
    public Application configure() {
        Map<String, Object> mapProp = new HashMap<String, Object>();
        mapProp.put("message", "HelloWorld");
        return new ResourceConfig(ConfigurationResource.class)
                .setProperties(mapProp);
    }

    @Test
    public void testGetConfiguration() {
        String response = ClientBuilder.newClient()
                .target("http://localhost:9998/configuration")
                .request(MediaType.TEXT_PLAIN)
                .get(String.class);
        System.out.println(response);
    }
}

这是运行此测试所需的唯一依赖项:

    <dependency>
        <groupId>org.glassfish.jersey.test-framework.providers</groupId>
        <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
        <version>2.13</version>
    </dependency>

您应该将此视为结果

============
message : HelloWorld
=============