【问题标题】:how to get web context path in spring mvc + maven project?如何在 spring mvc + maven 项目中获取 web 上下文路径?
【发布时间】:2019-04-21 13:37:05
【问题描述】:

我使用tomcat7-maven-plugin启动我的spring mvc项目,并尝试通过下面获取spring控制器中的完整路径。

 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没有关系,任何java web app如果无法获取servletContext,都可以获取这样的上下文路径。

但如果我通过“mvn tomcat7:run”以开发模式启动项目。它会给我下面的路径。

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

然后我无法通过这个 url 获取上下文路径。我想知道当我通过 maven 启动项目时上下文根在哪里,我怎样才能得到它?谢谢。

【问题讨论】:

  • 你为什么需要这个?看起来你正在做你一开始就不应该做的事情(或者至少使用不同的方式)。

标签: java spring maven


【解决方案1】:
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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多