在JAX-RS请求之间共享变量

Fre*_*ier 5 java jax-rs apache-wink

我认为这是一个关于JAX-RS的一个非常基本的问题,但我不知道怎么也找不到答案.

我正在尝试重构REST服务,该服务使用"标准"Javax servlet - 将请求手动路由到方法 - 进入"更干净"的JAX-RS实现.当前应用程序在servlet init()期间设置一些变量.它将它们分配为HttpServlet类的属性,以便它们在每个doGet()期间可用,并且可以作为参数传递给请求处理方法.为清楚起见,其中一个是ConcurentHashMap,它充当缓存.

现在,使用JAX-RS,我可以扩展Application来设置我的资源类.我还可以在每个资源实现中使用@Context注释在处理请求时注入ServletContext之类的东西.但我不知道如何在应用程序初始化期间类似地注入变量集.

我正在使用JAX-RS的Apache Wink 1.3.0实现.

Pau*_*gas 5

您可以使用侦听器初始化缓存,并在Web应用程序启动之前将上下文设置为属性.类似以下内容:

package org.paulvargas.shared;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class CacheListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) {
        Map<String, String> dummyCache = new HashMap<String, String>();
        dummyCache.put("greeting", "Hello Word!");

        ServletContext context = sce.getServletContext();
        context.setAttribute("dummyCache", dummyCache);
    }

    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        context.removeAttribute("dummyCache");
    }

}
Run Code Online (Sandbox Code Playgroud)

此侦听器配置在web.xml.

<listener>
    <listener-class>org.paulvargas.shared.CacheListener</listener-class>
</listener>
<servlet>
    <servlet-name>restSdkService</servlet-name>
    <servlet-class>
        org.apache.wink.server.internal.servlet.RestServlet
    </servlet-class>
    <init-param>
        <param-name>applicationConfigLocation</param-name>
        <param-value>/WEB-INF/application</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>restSdkService</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Run Code Online (Sandbox Code Playgroud)

您可以使用@Context注释来注入ServletContext和检索属性.

package org.apache.wink.example.helloworld;

import java.util.*;

import javax.servlet.ServletContext;
import javax.ws.rs.*;
import javax.ws.rs.core.*;

import org.apache.wink.common.model.synd.*;

@Path("/world")
public class HelloWorld {

    @Context
    private ServletContext context;

    public static final String ID = "helloworld:1";

    @GET
    @Produces(MediaType.APPLICATION_ATOM_XML)
    public SyndEntry getGreeting() {

        Map<String, String> dummyCache = 
                       (Map<String, String>) context.getAttribute("dummyCache");

        String text = dummyCache.get("greeting");

        SyndEntry synd = new SyndEntry(new SyndText(text), ID, new Date());
        return synd;
    }

}
Run Code Online (Sandbox Code Playgroud)