代码之家  ›  专栏  ›  技术社区  ›  liam xu

如何在spring mvc+maven项目中获取web上下文路径?

  •  0
  • liam xu  · 技术社区  · 6 年前

    我正在使用tomcat7 maven插件启动我的spring mvc项目,并尝试在下面的spring controller中获取完整路径。

     String path = this.getClass().getClassLoader().getResource("").getPath();
    

    C:/Users/xxxxx/Documents/xxx/apache-tomcat-8.5.31/webapps/showcase/WEB-INF/classes/
    

    然后我可以通过 fullPath.split("/WEB-INF/classes/") .

    但是如果我在开发模式下启动这个项目 '. 它会给我下面的路。

    C:/git/xxxxx/showcase/target/classes
    

    然后我无法通过这个url获取上下文路径。我想知道当我用maven启动项目时,上下文根在哪里,以及如何获得它?谢谢。

    1 回复  |  直到 6 年前
        1
  •  0
  •   user9697960 user9697960    6 年前
    public static File upload(MultipartFile file, HttpServletRequest request, boolean file_name, String upload_folder) {
            String filename = null;
            File serverFile = null;
            try {
                String applicationpath = request.getServletContext().getRealPath("");
                filename = file.getOriginalFilename();
                byte[] bytes = file.getBytes();
                String rootPath = applicationpath;
                File dir = new File(rootPath + File.separator + upload_folder);
                if (!dir.exists())
                    dir.mkdirs();
                serverFile = new File(dir.getAbsolutePath() + File.separator + filename);
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
                return serverFile;
            } catch (Exception e) {
                serverFile = null;
            }
            return serverFile;
        }