繁体   English   中英

如何在Spring MVC + Maven项目中获取Web上下文路径?

[英]how to get web context path in spring mvc + maven project?

我正在使用tomcat7-maven-plugin启动我的spring mvc项目,并尝试通过下面的方法获取spring控制器中的fullpath。

 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/")获得上下文路径。 实际上,它与springmvc无关,如果无法获取ServletContext,则任何Java Web应用程序都可以获取这样的上下文路径。

但是如果我通过' mvn tomcat7:run '在dev模式下启动项目。 它将为我提供如下路径。

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

然后,我无法通过该URL获取上下文路径。 我想知道通过Maven启动项目时上下文根在哪里,如何获得它? 谢谢。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM