【问题标题】:How to reach the WebContent folder from a web service method如何从 Web 服务方法访问 WebContent 文件夹
【发布时间】:2012-04-09 19:16:00
【问题描述】:

我想从同一项目中的 Web 服务中的方法访问 WebContent 文件夹中的文件。例如:

@WebMethod
public String test() {
     File configFile = new File("config.xml");
     return configFile.getAbsolutePath();
}

它返回“/usr/share/glassfish3/glassfish/domains/domain1/config/config.xml”。我想访问目录“/usr/share/glassfish3/glassfish/domains/domain1/applications/my_project_name/”文件夹中的文件。我怎样才能得到它?

【问题讨论】:

标签: java jax-ws


【解决方案1】:

根据您的代码,我了解到您的代码是 JAXWS 网络服务。

在jaxws中,可以获取HttpServletRequest、HttpServletResponse、ServletContext,

在你的 webservice 类中有一个私有变量并以这种方式注释它

@Resource
private WebServiceContext context;

然后在您的方法中,您可以通过这种方式获取 ServletContext

ServletContext servletContext =
    (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);

从servletContext,你可以得到路径。

假设如果需要获取HttpServletRequest,可以这样获取

HttpServletRequest request =
            (HttpServletRequest) context.getMessageContext().get(MessageContext.SERVLET_REQUEST);

你可以像这样获得应用的上下文路径

request.getContextPath() ;

【讨论】:

  • 感谢您的回答。我使用这个语句来创建一个新文件,但它不起作用:String filePath = String.format("%s%s%s", request.getContextPath(), File.separatorChar, "config.xml"); File configFile = new File(filePath);
  • 尝试将其作为输入流来获取:例如 ServletContext servletContext = (ServletContext) context .getMessageContext().get(MessageContext.SERVLET_CONTEXT); FileInputStream fis = new FileInputStream(servletContext.getContextPath() + "/" + fileName);
【解决方案2】:

将以下参数添加到您的 Web 服务类:

@Context
ServletContext context;

那么,假设你的config.xml文件在WebContent文件夹中,你可以通过调用context.getRealPath(String)方法得到它的绝对路径。使用您的示例代码将是:

@WebMethod
public String test() {
     File configFile = new File(context.getRealPath("config.xml"));
     return configFile.getAbsolutePath();
}

或者直接,不通过 File 对象:

@WebMethod
public String test() {
     return context.getRealPath("config.xml");
}

【讨论】:

    【解决方案3】:

    我使用的最佳方法是:

    Thread.currentThread().getContextClassLoader().getResource("myFile.txt").getPath()
    

    这给出了放置在 WebApp 的 WebContent 文件夹内的 /WEB-INF/classes/ 目录中的任何文件 myFile.txt 的路径。

    在 Eclipse JEE 环境中,您需要将文件myFile.txt 保存在src 文件夹中,以便部署者将其传输到/WEB-INF/classes/ 文件夹中。

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      相关资源
      最近更新 更多