栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您可以使用侦听器来初始化缓存,并在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");    }}

该侦听器在中配置

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>

您可以使用

@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;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/573989.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号