从 java 类文件获取 apache webcontents 文件夹的绝对路径

发布于 2024-12-06 03:41:59 字数 299 浏览 0 评论 0原文

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

  • 实际上我需要获取 apache webapps 文件夹的路径...部署 webapps 的路径

  • eg /apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg

  • 需要在 java 类文件中获取它,而不是在 jsp 页面或任何视图页面上。

有什么想法吗?

Need to get absolute path in java class file, inside a dynamic web application...

  • Actually i need to get path of apache webapps folder... where the webapps are deployed

  • e.g. /apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg

  • Need to get this in a java class file, not on jsp page or any view page...

any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

雾里花 2024-12-13 03:41:59

实际上我需要获取 apache webapps 文件夹的路径...部署 webapps 的位置

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

正如许多其他答案所提到的,您可以只使用 ServletContext#getRealPath () 将相对 Web 内容路径转换为绝对磁盘文件系统路径,以便您可以在 FileFileInputStream 中进一步使用它。 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");
// ...

另请参阅:

Actually i need to get path of apache webapps folder... where the webapps are deployed

e.g. /apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg

As mentioned by many other answers, you can just use ServletContext#getRealPath() to convert a relative web content path to an absolute disk file system path, so that you could use it further in File or FileInputStream. The ServletContext is in servlets available by the inherited getServletContext() method:

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

However, the filename "imagetosave.jpg" indicates that you're attempting to store an uploaded image by FileOutputStream. The public webcontent folder is the wrong place to store uploaded images! They will all get lost whenever the webapp get redeployed or even when the server get restarted with a cleanup. The simple reason is that the uploaded images are not contained in the to-be-deployed WAR file at all.

You should definitely look for another location outside the webapp deploy folder as a more permanent storage of uploaded images, so that it will remain intact across multiple deployments/restarts. Best way is to prepare a fixed local disk file system folder such as /var/webapp/uploads and provide this as some configuration setting. Finally just store the image in there.

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

See also:

梦里兽 2024-12-13 03:41:59

如果您有 javax.servlet.ServletContext 您可以调用:

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

来获取图像存储位置的实际路径。

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

但是,您可能想考虑使用:

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

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

If you have a javax.servlet.ServletContext you can call:

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

to get the actual path of where the image is stored.

ServletContext can be accessed from a javax.servlet.http.HttpSession.

However, you might want to look into using:

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

or

servletContext.getResourceAsStream("/images/imagetosave.jpg") 
初与友歌 2024-12-13 03:41:59
String path =  MyClass.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

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

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

This should return your absolute path based on the class's file location.

樱花坊 2024-12-13 03:41:59

方法-1:

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

InetAddress ip = InetAddress.getLocalHost();

//step2 : 提供您的文件路径

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

//step3 : 将所有部分放在一起

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

Method - 2 :

//Step : 1-获取绝对 url

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

//Step : 2-然后将其与上下文路径进行子串

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

//step : 3-在Web文件夹后提供您的文件路径

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

我的建议

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

玩得开心

Method -1 :

//step1 : import java.net.InetAddress;

InetAddress ip = InetAddress.getLocalHost();

//step2 : provide your file path

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

//step3 : grab all peices together

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

Method - 2 :

//Step : 1-get the absolute url

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

//Step : 2-then sub string it with the context path

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

//step : 3-provide your file path after web folder

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

MY SUGGESTION

  1. keep the file which you want to open in the default package of your source folder and open the file directly to make things simple and clear.
    NOTE : this happens because it is present in the class path of your IDE if you are coding without IDE then keep it in the place of your java compiled class file or in a common folder which you can access.

HAVE FUN

雪花飘飘的天空 2024-12-13 03:41:59

我能够在过滤器中获得对 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>

I was able to get a reference to the ServletContext in a Filter. What I like best about this approach is that it occurs in the init() method which is called upon the first load the web application meaning the execution only happens once.

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;
}

I added the "templatepath" to the filterConfig via the web.xml:

<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>
信愁 2024-12-13 03:41:59

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

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
}

You can get path in controller:

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
}
千年*琉璃梦 2024-12-13 03:41:59

您可以编写一个 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>

You could write a 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
    }

    //...
}

and configure it in web.xml

<listener>
    <listener-class>my.package.MyServletContextListener</listener-class>
</listener>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文