简体   繁体   English

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

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

I was using tomcat7-maven-plugin to start my spring mvc project, and try to get the fullpath in spring controller by below. 我正在使用tomcat7-maven-plugin启动我的spring mvc项目,并尝试通过下面的方法获取spring控制器中的fullpath。

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

It will give me the path like below. 它将为我提供如下路径。

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

Then I can get the context path by fullPath.split("/WEB-INF/classes/") . 然后,我可以通过fullPath.split("/WEB-INF/classes/")获得上下文路径。 Actually it has nothing to do with springmvc, any java web app can get context path like this if cannot get the servletContext. 实际上,它与springmvc无关,如果无法获取ServletContext,则任何Java Web应用程序都可以获取这样的上下文路径。

But if I start the project in dev mode by ' mvn tomcat7:run '. 但是如果我通过' mvn tomcat7:run '在dev模式下启动项目。 It will give me the path like below. 它将为我提供如下路径。

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

Then I can not get the context path by this url. 然后,我无法通过该URL获取上下文路径。 I want to know where is the context root when I start the project by maven and how can I get it? 我想知道通过Maven启动项目时上下文根在哪里,如何获得它? Thanks. 谢谢。

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