简体   繁体   中英

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.

 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/") . Actually it has nothing to do with springmvc, any java web app can get context path like this if cannot get the servletContext.

But if I start the project in dev mode by ' mvn tomcat7:run '. 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. I want to know where is the context root when I start the project by maven and how can I get it? 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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