【问题标题】:How to create/write to file in class namespace under web-inf/class如何在 web-inf/class 下的类命名空间中创建/写入文件
【发布时间】:2012-07-13 12:16:27
【问题描述】:

我编写了以下内容以将对象缓存到类资源位置。

static private <T> void toSerializedCache(Class<T> cls, T t, String cachecrlstr) {
  try {
    URL crl = cls.getResource(cachecrlstr);
    File crf = new File(crl.getFile());

    JAXBContext jaxbContext = JAXBContext.newInstance(cls);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(t, crf);
  }
  catch (Exception e) {
    System.out.printf("Failed to write %s to cache %s", t.getClass(), cachecrlstr);
  }
}

问题是 cachecrlstr 是一个最初不存在的文件。该文件必须最初创建。

由于它最初不存在,因此类加载器会将 url 返回为 null 并且过程失败。

我不能使用绝对路径,因为此例程在 Web 服务上运行,我们需要从类加载器推导出绝对路径。

为了解决这个问题,我把例程改写成

static private <T> void toSerializedCache(Class<T> cls, T t, String cachecrlstr) {
  try {
    File crf = new File(request.getSession().getServletContext().getRealPath("/WEB-INF/class"+cachecrlstr));

    JAXBContext jaxbContext = JAXBContext.newInstance(cls);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(t, file);
  }
  catch (JAXBException e) {
    System.out.printf("Failed to write %s to cache %s", t.getClass(), cachecrlstr);
  }
}

但我无法获取 httpservletrequest 对象,因为此例程位于 jax-rs 服务实现中。而且我不愿意编写一个http监听器(那些在web.xml中注册的)来将请求存储到Threadlocal映射中。 (意思是,不想乱维护 Threadlocal 对象)。

但是,(虽然不愿意给它写信)我愿意从 Threadlocal 中撤回对象。

有谁知道 RestEasy 是否在 Threadlocal 中存储了我可以撤回以推断会话上下文或请求的任何 http 对象?

更重要的问题是 - 你建议我做什么来将对象写入文件,其中文件路径相对于WEB-INF/class,在我上面提到的约束下。

【问题讨论】:

    标签: java http file-io resteasy thread-local


    【解决方案1】:

    您可以从ResteasyProviderFactory 检索HttpServletRequest

    HttpServletRequest request = (HttpServletRequest) ResteasyProviderFactory.getContextDataMap().get(HttpServletRequest.class);
    

    或者,如果您在 JAX-RS 服务或拦截器中,RESTEasy 可以为您注入 HttpServletRequest

    @javax.ws.rs.core.Context
    HttpServletRequest request;
    

    【讨论】:

      猜你喜欢
      • 2013-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      相关资源
      最近更新 更多