你的位置:首页 > 软件开发 > ASP.net > 在class中获取web资源

在class中获取web资源

发布时间:2015-12-14 10:00:04
背景介绍 项目中用jasperreport做报表,模板文件为web资源,不在classpath之中。class又需要获取模板文件,结合数据源,生成pdf格式的报表。 之前的做法是定义一个public static byte[] getPdfBytes(HttpServletReq ...

背景介绍

项目中用jasperreport做报表,模板文件为web资源,不在classpath之中。class又需要获取模板文件,结合数据源,生成pdf格式的报表。

之前的做法是定义一个public static byte[] getPdfBytes(HttpServletRequest request)的接口,以request.getServletContext().getRealPath(String relativePath)的方式获取web资源的绝对路径,再根据绝对路径获取资源。

这样一来,这个方法的调用者就直接或者间接的受限于Servlet,或者说这个方法就是专门为Servlet而准备的。

我们理想中的接口是这样的public InputStream getResource(String relativePath),只需要正确的相对路径,就可以获取对应资源的内容。

基于Servlet的方案

1、定义ServletContextListener,缓存ServletContext

package cn.ljl.javaweb.demo.util;import javax.servlet.ServletContext;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.servlet.annotation.WebListener;/** * 用于缓存并提供当前{@link ServletContext}. * @author lijinlong * */@WebListenerpublic class ServletContextHolder implements ServletContextListener {    private static ServletContext context;  /**   * @return the context   */  public static ServletContext getContext() {    return context;  }  @Override  public void contextInitialized(ServletContextEvent sce) {    context = sce.getServletContext();  }  @Override  public void contextDestroyed(ServletContextEvent sce) {    context = null;  }}

原标题:在class中获取web资源

关键词:web

web
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。