Jersey JAX-RS独立服务器 - 如何将参数传递给请求处理程序?

时间:2016-01-18 15:18:26

标签: java jersey server

我构建了一个简单的Jersey休息服务器,它处理一个简单的服务。 在启动服务器的主类中,我读取了我想要的属性文件 提供/传递给jax处理程序类。 服务器工作,我只需要一种方式来共享配置参数 带有请求处理程序的主类。 我怎么能这样做?

main的代码,我只读了一次de properties文件:

...

public HashMap resources;

// this start the listener jersey server...
String host="http://localhost/";
int port = 9998;
URI baseUri = UriBuilder.fromUri(host).port(port).build();
ResourceConfig config = new ResourceConfig();
config.packages(true, "br.com.myserver");
config.register(MyHandler.class);

// I WANT TO ACCESS/SHARE THIS WITH THE HANDLER -> MyHandler.class
resources.put("host_user","bla bla bla");

HttpServer server = JdkHttpServerFactory.createHttpServer(baseUri, config);

System.out.println("--Press Enter to STOP the server--");
System.in.read();
Server.stop(0);
System.out.println("Server stoped!");
...

MyHandler的代码,我想访问主要属性:

@Path("myapp")
public class MyHandler
{
    @POST @Path("/testep")
    @Consumes("application/json")
    @Produces("text/plain")
    public String action1(@Context Request request, String json) 
    {
        // HERE I WANT TO ACCESS THE RESOUCES HASHMAP OF MAIN HERE
        // (how get main handler here).resources.get("host_user");

        // maybe access main class, or something like
        // the intention is to avoid the read of config at all requests here

        System.out.println("received event:" + json);
        return "event received " + json;
    }
}

任何想法都会被贬低,谢谢。

1 个答案:

答案 0 :(得分:1)

您使用ResourceConfig配置property(key, value)的任何属性都可以通过Configuration界面访问,您可以将其注入资源类。

ResourceConfig config = new ResourceConfig();
config.property("host_user","bla bla bla");
...
@Path("myapp")
public class MyHandler
{
    @Context
    Configuration configuration;

    public String action1(@Context Request request, String json) {
        Map<String, Object> props = configuration.getProperties();
    }
}

另见: