How can I get real path for file in my WebContent folder?

前端 未结 9 991
既然无缘
既然无缘 2020-12-16 02:33

I need to get real path for file in my WebContent directory, so that framework that I use can access that file. It only takes String file as attribute, so I need to get the

相关标签:
9条回答
  • 2020-12-16 03:11

    Include the request as a parameter. Spring will then pass the request object when it calls the mapped method

    @RequestMapping .....
    public String myMethod(HttpServletRequest request) {
       String realPath = request.getRealPath("/somefile.txt");
       ...
    
    0 讨论(0)
  • 2020-12-16 03:12

    This approach uses the resource loader to get the absolute path to a file in your app, and then goes up a few folders to the app's root folder. No servlet context required! This should work if you have a "web.xml" in your WEB-INF folder. Note that you may want to consider using this solely for development, as this type of configuration is usually best stored externally from the app.

    public String getAppPath()
    {
        java.net.URL r = this.getClass().getClassLoader().getResource("web.xml");
        String filePath = r.getFile();
        String result = new File(new File(new File(filePath).getParent()).getParent()).getParent();
    
        if (! filePath.contains("WEB-INF"))
        {
            // Assume we need to add the "WebContent" folder if using Jetty.
            result = FilenameUtils.concat(result, "WebContent");
        }
    
        return result;
    }
    
    0 讨论(0)
  • 2020-12-16 03:12

    try to use this when you want to use arff.txt in your development and production level too

      String path=getServletContext().getRealPath("/WEB-INF/files/arff.txt");
    
    0 讨论(0)
提交回复
热议问题