get absolute path to apache webcontents folder from a java class file [duplicate]

谁说胖子不能爱 提交于 2020-01-01 02:40:15

问题


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?


回答1:


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:

  • What does servletcontext.getRealPath("/") mean and when should I use it
  • Where to place and how to read configuration resource files in servlet based application?
  • Simplest way to serve static data from outside the application server in a Java web application



回答2:


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") 



回答3:


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

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




回答4:


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>



回答5:


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
}



回答6:


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




回答7:


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>


来源:https://stackoverflow.com/questions/7517401/get-absolute-path-to-apache-webcontents-folder-from-a-java-class-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!