我炮制了以下代码以将对象缓存到类资源位置。如何在web-inf/class下的类名称空间中创建/写入文件
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
,在上述限制条件下。