从Java类文件获取Apache Web内容文件夹的绝对路径

10

需要在Java类文件中获取动态Web应用程序内的绝对路径...

  • 实际上,我需要获取Apache WebApps文件夹的路径...即WebApps部署的位置

  • 例如:/ apache-root / webapps / my-deployed-app / WebContent / images / imagetosave.jpg

  • 需要在Java类文件中获取此路径,而不是在JSP页面或任何视图页面中...

有什么想法吗?

7个回答

12

实际上我需要获取Apache Web应用程序文件夹的路径......那里是Web应用程序部署的地方。

例如:/apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg

如其他答案所述,您可以使用ServletContext#getRealPath()将相对Web内容路径转换为绝对磁盘文件系统路径,以便在FileFileInputStream中进一步使用。在Servlet中,ServletContext可通过继承的getServletContext()方法获得:

String relativeWebPath = "/images";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath, "imagetosave.jpg");
// ...

然而,文件名"imagetosave.jpg"表明您正在尝试通过FileOutputStream存储已上传的图像。公共webcontent文件夹是存储已上传的图像的错误位置!每当Web应用程序重新部署或甚至在服务器进行清理时,它们都将丢失。简单的原因是已上传的图像根本没有包含在要部署的WAR文件中。

您应该绝对寻找另一个位置外部的webapp部署文件夹,作为已上传图像的更持久的存储位置,以便它可以跨多个部署/重启保持完好无损。最好的方法是准备一个固定的本地磁盘文件系统文件夹,例如/ var / webapp / uploads ,并将其提供为一些配置设置。最后只需将图像存储在其中即可。

String uploadsFolder = getItFromConfigurationFileSomehow(); // "/var/webapp/uploads"
File file = new File(uploadsFolder, "imagetosave.jpg");
// ...

另请参阅:


拯救了我的生命!谢谢! - TejjD
在这种情况下,浏览器能够异步下载图像吗?就像WebContent的情况一样,我们可以简单地放置img src = ""吗?这里怎么处理? - Gaurav
@Paras:请看最后一个“另请参阅”的链接。 - BalusC
我在我的评论后面加了一个“:P”。 - Gaurav
简洁可靠的答案。谢谢! - ethane
只是一个想法 - 如果请求被MultiPartRequestWrapper覆盖,您不能使用getServletContext(),因为MultipartRequestWrapper实现没有正确地重写该方法。我曾经遇到过这个错误。 - ha9u63a7

2
如果您拥有一个javax.servlet.ServletContext,您可以调用以下方法:
servletContext.getRealPath("/images/imagetosave.jpg")

获取图像实际存储路径的方法:

可以从javax.servlet.http.HttpSession中访问ServletContext。

但是,您可能需要考虑使用以下方法:

servletContext.getResource("/images/imagetosave.jpg")

或者

servletContext.getResourceAsStream("/images/imagetosave.jpg") 

2
String path =  MyClass.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

根据类文件的位置,这应该返回您的绝对路径。


2

方法一:

//步骤1:导入java.net.InetAddress包;

InetAddress ip = InetAddress.getLocalHost();

//步骤2:提供您的文件路径

String filepath="GIVE YOUR FILE PATH AFTER WEB FOLDER something like /images/grid.png"

//步骤3:将所有部分组合在一起

String a ="http://"+ip.getHostAddress()+":"+request.getLocalPort()+""+request.getServletContext().getContextPath()+filepath;

方法二:

//步骤1:获取绝对URL

String path = request.getRequestURL().toString();

//步骤:2-然后使用上下文路径对其进行子字符串处理

path = path.substring(0, path.indexOf(request.getContextPath()));

//步骤:3-在web文件夹后提供您的文件路径

String finalPath = "GIVE YOUR FILE PATH AFTER WEB FOLDER something like /images/grid.png"
path +=finalPath;

我的建议

  1. 将要打开的文件保留在源文件夹的默认包中,并直接打开文件,以使事情变得简单明了。
    注意:如果您没有使用IDE进行编码,则是因为它存在于IDE的类路径中。在没有IDE的情况下,请将其保留在Java编译类文件所在的位置或可以访问的公共文件夹中。

祝您愉快!


1

我能够在过滤器中获取ServletContext的引用。我最喜欢这种方法的原因是它发生在init()方法中,该方法在首次加载Web应用程序时调用,这意味着执行只会发生一次。

public class MyFilter implements Filter {
    protected FilterConfig filterConfig;
    public void init(FilterConfig filterConfig) {
        String templatePath = filterConfig.getServletContext().getRealPath(filterConfig.getInitParameter("templatepath"));
        Utilities.setTemplatePath(templatePath);
        this.filterConfig = filterConfig;
}

我通过web.xml将“templatepath”添加到filterConfig中:
<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>com.myapp.servlet.MyFilter</filter-class>
    <init-param>
        <param-name>templatepath</param-name>
        <param-value>/templates</param-value>
    </init-param>
</filter>    
<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

1

你可以在控制器中获取路径:

public class MyController extends MultiActionController {
private String realPath;

public ModelAndView handleRequest(HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    realPath = getServletContext().getRealPath("/");
    String classPath = realPath + "WEB-INF/classes/" + MyClass.ServletContextUtil.class.getCanonicalName().replaceAll("\\.", "/") + ".java";
    // add any code
}

0
你可以编写一个ServletContextListener:
public class MyServletContextListener implements ServletContextListener
{

    public void contextInitializedImpl(ServletContextEvent event) 
    {
        ServletContext servletContext = event.getServletContext();
        String contextpath = servletContext.getRealPath("/");

        // Provide the path to your backend software that needs it
    }

    //...
}

并在web.xml中进行配置

<listener>
    <listener-class>my.package.MyServletContextListener</listener-class>
</listener>

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