如何从Web服务方法访问WebContent文件夹

4

我希望从同一项目中的 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/" 目录下的文件。请问如何访问?

如何获取基本URL - Riddhish.Chaudhari
3个回答

2
我使用的最佳方法是:
Thread.currentThread().getContextClassLoader().getResource("myFile.txt").getPath()

这将给出任何位于WebApp的WebContent文件夹内的/WEB-INF/classes/目录中的文件myFile.txt的路径。

在Eclipse JEE环境中,您需要将您想要在Web服务中读取的文件myFile.txt放在src文件夹中,以便由部署程序将其传输到/WEB-INF/classes/文件夹中。


1
从你的代码中,我了解到你的是一个JAXWS Web服务。
在jaxws中,你可以获取HttpServletRequest、HttpServletResponse、ServletContext,
在你的Web服务类中定义一个私有变量,并以这种方式注释它。
@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() ;

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

1
将以下参数添加到您的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();
}

直接进行操作,无需通过文件对象:
@WebMethod
public String test() {
     return context.getRealPath("config.xml");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接